【发布时间】:2012-05-17 14:37:29
【问题描述】:
我是 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 语句中执行代码。
我确实做错了,需要了解如何达到上述目标的确切步骤。
提前谢谢你。 朱利安
【问题讨论】:
-
你还没告诉我们问题出在哪里。
-
这个来自 msdn 的示例为我取消了 msdn.microsoft.com/en-us/library/dd997396
标签: c# .net multithreading task