简体   繁体   English

如何在C#中停止运行任务

[英]How to stop running task in C#

I have a running task and need to make a feature that user can stop the running task anytime. 我有一个正在运行的任务,需要创建一个用户可以随时停止正在运行的任务的功能。 I tried to token.Cancel(); 我试过token.Cancel(); but still didn't work. 但仍然没有奏效。

here is my code: 这是我的代码:

var task = new Task(new Action(Method), tokenSource2.Token);
 var cToken = tokenSource2.Token;
cToken.Register(() => cancelNotification());

// code to stop the running task .. button click event

 if (tokenSource2 != null)
            {

                tokenSource2.Cancel();


            }

I believe for cancellation tokens to work, the method being called as the body of the task needs to accept a cancellation token and constantly check if it has been cancelled between each step of logic. 我相信取消令牌工作,被调用的方法作为任务的主体需要接受取消令牌并不断检查它是否在每个逻辑步骤之间被取消。 See here for more details . 有关详细信息,请参见此处

This example is an excerpt from that document and outlines how to check the status of a cancellation token. 此示例摘自该文档,并概述了如何检查取消令牌的状态。

using System;
using System.Threading;

public class Example
{
   public static void Main()
   {
      // Create the token source.
      CancellationTokenSource cts = new CancellationTokenSource();

      // Pass the token to the cancelable operation.
      ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomeWork), cts.Token);
      Thread.Sleep(2500);

      // Request cancellation.
      cts.Cancel();
      Console.WriteLine("Cancellation set in token source...");
      Thread.Sleep(2500);
      // Cancellation should have happened, so call Dispose.
      cts.Dispose();
   }

   // Thread 2: The listener
   static void DoSomeWork(object obj)
   {
      CancellationToken token = (CancellationToken)obj;

      for (int i = 0; i < 100000; i++) {
         if (token.IsCancellationRequested)
         {
            Console.WriteLine("In iteration {0}, cancellation has been requested...",
                              i + 1);
            // Perform cleanup if necessary.
            //...
            // Terminate the operation.
            break;
         }
         // Simulate some work.
         Thread.SpinWait(500000);
      }
   }
}
// The example displays output like the following:
//       Cancellation set in token source...
//       In iteration 1430, cancellation has been requested...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM