我在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语句中执行代码。
我明确地认为smth错误,并且需要确切的步骤来实现上述目标。
提前谢谢你。 儒略
答案 0 :(得分:0)
我认为你需要这样的东西:
while (!ct.IsCancellationRequested /* or all work is done*/)
{
Console.WriteLine("DoSomeWork");
}
Console.WriteLine("We were cancelled.");