【问题标题】:How to cancel a threaded task according to app condition如何根据应用条件取消线程任务
【发布时间】: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 语句中执行代码。

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

提前谢谢你。 朱利安

【问题讨论】:

标签: c# .net multithreading task


【解决方案1】:

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


while (!ct.IsCancellationRequested /* or all work is done*/)
{
    Console.WriteLine("DoSomeWork");
}
Console.WriteLine("We were cancelled.");

【讨论】:

  • 主要思路是将主要任务拆分成部分,每部分完成后检查ct.IsCancellationRequested。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-02
  • 1970-01-01
相关资源
最近更新 更多