C#对每个创建的任务使用取消令牌

问题描述

我有一个task方法,该方法会在MainWindow中生成温度曲线,但是当用户将大量(生产的物品)数据输入烤箱并每30秒记录一次温度时,就会以另一种形式调用该方法。

public static async Task genLotProfile(string lotno,string filename,string datch,CancellationToken token)

try
{
       //get temperature and do other stuff
       Tprofile temp = getLogData(datch); 
       
       //task delay
       while (!token.IsCancellationRequested)
      {
          //Task delay
          await Task.Delay(30000,token);
      }
}
catch (OperationCanceledException e)
{

}

我的想法是每次输入很多时在输入表单中的回车按钮功能上调用它。

private void EnterBtn_Click(object sender,RoutedEventArgs e)
{
   //do other stuff

   //Call generate temp profile
    string filename = MainWindow.getTempProfileName(MainWindow.datachannel,lotnoTBX.Text);
                
    CancellationToken token = source.Token;
                
    MainWindow.genLotProfile(lotnoTBX.Text,filename,MainWindow.datachannel,token);
}

我还有一个单独的取消课程

    class Cancel
    {
        CancellationTokenSource _source;

        public Cancel(CancellationTokenSource source)
        {
            _source = source;
        }

        public void cancelTask()
        {
            _source.Cancel();
        }
    }

问题是,我将在自己的条件下运行多个任务,并且当用户从烤箱中取出很多东西时,我想使用另一种输出形式上的Cancel类杀死特定任务,如果发生以下情况,取消令牌会杀死我所有正在运行的任务我执行以下操作

CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
Cancel c = new Cancel(source); 
c.cancelTask();

解决方法

您需要为每个任务创建新的CancellationTokenSource:

private async void EnterBtn_Click(object sender,RoutedEventArgs e)
{
   //do other stuff

   //Call generate temp profile
    string filename = MainWindow.getTempProfileName(MainWindow.datachannel,lotnoTBX.Text);

    CancellationTokenSource source = new CancellationTokenSource();                
    CancellationToken token = source.Token;
                
    await MainWindow.genLotProfile(lotnoTBX.Text,filename,MainWindow.datachannel,token);
}

取消特定任务时,只需要在令牌的正确实例上调用cancel()。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...