基于TPL的异步编程,最简单的就是使用Task对象,而创建一个Task对象,最简单的就是使用lamda表达式:
static void Main(string[] args) {
// create the cancellation token source
CancellationTokenSource tokenSource = new CancellationTokenSource();
// create the cancellation token
CancellationToken token = tokenSource.Token;
int i = 0;
int value = 10;
// create the first task, which we will let run fully
Task task1 = new Task(() => {
for (i = 0; i < Int32.MaxValue; i++)
{
value++;
bool cancelled = token.WaitHandle.WaitOne(10000);
if (cancelled) {
throw new OperationCanceledException(token);
}
}
}, token);
// start task