1

我在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 语句中执行代码。

我确实做错了,需要如何达到上述目标的确切步骤。

先感谢您。朱利安

4

1 回答 1

0

我认为你需要类似的东西:


while (!ct.IsCancellationRequested /* or all work is done*/)
{
    Console.WriteLine("DoSomeWork");
}
Console.WriteLine("We were cancelled.");
于 2012-05-17T14:45:34.130 回答