简体   繁体   English

在asp.net中取消任务

[英]Cancel task in asp.net

I have a function that generate 35 task for Calculation of invoices. 我有一个函数可以生成35个发票计算任务。

My code : 我的代码:

  public int CalcGroup()
        {
            try
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                CancellationToken ct = cts.Token;

                for (int i = 0; i < 35 ; i++)
                {

                   var myTask = new Task<long>(() =>   CalcSingle(_personnelIds.Item1), ct, TaskCreationOptions.LongRunning);
                        myTask.Start();

                }
            }
            catch (Exception)
            {
                return 0;
            }
            return 1;
        } 

"CalcSingle() is another function that tasks working on it." “ CalcSingle()是另一个在其上工作的函数。” and my event for cancel the tasks is : 我取消任务的事件是:

 protected void btnStopCalc_Click(object sender, EventArgs e)
        {                             
            CancellationTokenSource cts = new CancellationTokenSource();
            cts.Cancel();
         }

It is not working correctly 它不能正常工作

An excerpt from MSDN: MSDN的摘录:

"A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. An object creates a cancellation token by using a CancellationTokenSource, and then passes the cancellation token to any number of threads or objects that should receive notice of cancellation. The token cannot be used to initiate cancellation. When the owning object calls Cancel on the CancellationTokenSource, the IsCancellationRequested property on every copy of the cancellation token is set to true. The objects that receive the notification can respond in whatever manner is appropriate." “一个CancellationToken启用线程,线程池工作项或Task对象之间的协作性取消。一个对象通过使用CancellationTokenSource创建一个取消令牌,然后将该取消令牌传递给应该接收取消通知的任何数量的线程或对象。令牌不能用于发起取消。当拥有对象在CancellationTokenSource上调用Cancel时,取消令牌的每个副本上的IsCancellationRequested属性都设置为true。接收通知的对象可以适当的方式进行响应。”

The point is that cancelling via a token only sets the "IsCancelled" property to true, your code in "CalcSingle" needs to poll that property after whatever logical steps in the code and exit gracefully. 关键是通过令牌取消只能将“ IsCancelled”属性设置为true,“ CalcSingle”中的代码需要在代码中执行逻辑步骤之后轮询该属性并正常退出。 This is done because .Net does not know whether your code is doing something critical and cancelling a task arbitrarily might leave your execution in a bad state. 这样做是因为.Net不知道您的代码是否正在执行关键任务,而任意取消任务可能会使您的执行处于不良状态。

look at: https://msdn.microsoft.com/en-us/library/dd997289(v=vs.110).aspx 查看: https : //msdn.microsoft.com/en-us/library/dd997289(v=vs.110).aspx

and this for a good example on how to do it for tasks (TPL): https://msdn.microsoft.com/en-us/library/dd997396(v=vs.110).aspx 这是关于如何完成任务(TPL)的一个很好的例子: https : //msdn.microsoft.com/en-us/library/dd997396 ( v= vs.110) .aspx

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

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