简体   繁体   English

如何取消正在使用 Task.Run() 运行的现有任务?

[英]How to cancel an existing task being run using Task.Run()?

The below mentioned UpdateMethod Can be called from various User actions like button UpdateSW1, UpdateSW2, UpdateSW3.下面提到的 UpdateMethod 可以从各种用户操作中调用,例如按钮 UpdateSW1、UpdateSW2、UpdateSW3。

If the User clicks on button UpdateSW1, it pauses the task for 10 seconds, waitTime is 2 here.如果用户点击按钮 UpdateSW1,它会暂停任务 10 秒,这里的 waitTime 是 2。 Now while this click is done, User Can click on UpdateSW2 also, when that happens, I want to cancel the ongoing delay or other operation of the Task as a result of first click (UpdateSW1) and start the operations for UpdateSW2.现在,当此单击完成时,用户也可以单击 UpdateSW2,当发生这种情况时,我想取消由于第一次单击 (UpdateSW1) 而导致的任务正在进行的延迟或其他操作,并启动 UpdateSW2 的操作。

private void UpdateMethod(int waitTime, int actionNo)
    {
        Task.Run(async () =>
        {
            while (waitTime != 0)
            {
                waitTime--;
                await Task.Delay(5000);
            }
            // DO other stuff ...

            if (actionNO == 1)
            {
                //ops for UpdateSW1
            }
            else
            {
                //ops for UpdateSW2.
            }
        });
    }

Update1:更新1:

After some trial I came up with following code, now this works fine to some extent, but still needs improvement.经过一番试验,我想出了以下代码,现在这在某种程度上可以正常工作,但仍需要改进。 What happens is if the user clicks on button UpdateSW1 and UpdateSW2 in a sequence and then i Click on the cancel button, it cancels one of the task (which is running as a result of UpdateSW1 click ) but does not cancel the other (one which is running as a result of click on updteSW2) I wish to cancel both the tasks.如果用户依次单击按钮 UpdateSW1 和 UpdateSW2 ,然后单击取消按钮,它会取消其中一个任务(由于 UpdateSW1 click 正在运行)但不取消另一个任务(其中一个由于单击 updteSW2 正在运行)我希望取消这两个任务。 How to achieve this.如何实现这一点。

Modified method:修改方法:

private CancellationTokenSource cts; // declared as class variable. 

private void UpdateMethod(int waitTime, int actionNo)
    {
        cts = new CancellationTokenSource();
        CancellationToken token1 = cts.Token;
        try
        {
            Task.Run(async () =>
            {
                while (waitTime != 0)
                {
                    waitTime--;
                    await Task.Run(() => Task.Delay(5000, token1), token1);
                    token1.ThrowIfCancellationRequested();
                }
                // DO other stuff ...

                if (actionNO == 1)
                {
                    //ops for UpdateSW1
                }
                else
                {
                    //ops for UpdateSW2.
                }
            }, token1);
        }
        catch (OperationCanceledException e)
        {
            // update DB log
        }
    }

This entire wait loop这整个等待循环

            while (waitTime != 0)
            {
                waitTime--;
                await Task.Run(() => Task.Delay(5000, token1), token1);
                token1.ThrowIfCancellationRequested();
            }

can be simplified to可以简化为

await Task.Delay(waitTime, token1);

When the token is signaled, the delay will end.当令牌发出信号时,延迟将结束。 No need to do that in a roundabout manner.无需以迂回的方式进行。

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

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