我在Task中很新,也许我的问题会很愚蠢,但我真的需要帮助。
我想根据应用情况取消任务。
好吧,我们开始:
static void Main(string[] args)
{
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
// Request cancellation from the UI thread.
if (Console.ReadKey().KeyChar == 'x')
{
tokenSource.Cancel();
}
Task.Factory.StartNew(() => DoSomeWork(token), token);
}
这里是我们的 DoSomeWork 方法:
static void DoSomeWork(CancellationToken ct)
{
// Was cancellation already requested?
if (ct.IsCancellationRequested)
{
Console.WriteLine("We were cancelled before we got started.");
Console.WriteLine("DoSomeWork() - Not Executed");
return;
}
Console.WriteLine("DoSomeWork() - Executed");
Console.ReadLine();
}
所以,我希望当我调用 tokenSource.Cancel();
这种情况将是真实的:
if (ct.IsCancellationRequested)
{
Console.WriteLine("We were cancelled before we got started.");
Console.WriteLine("DoSomeWork() - Not Executed");
return;
}
我将在 if 语句中执行代码。
我确实做错了,需要如何达到上述目标的确切步骤。
先感谢您。朱利安