在取消Task.Run时不会出现异常 [英] Exception is not caught at Cancelation of Task.Run

查看:137
本文介绍了在取消Task.Run时不会出现异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个课程 Worker 正在做一些工作(模拟工作量):

I have a class Worker which is doing some work (with simulated workload):

public class Worker
    { ...

public void DoWork(CancellationToken ct)
        {
            for (int i = 0; i < 10; i++)
            {
                ct.ThrowIfCancellationRequested();
                Thread.Sleep(2000);
            }
        }

现在我想使用这个方法在code> Task.Run (从我的Windows窗体应用程序,按钮点击),可以取消:

Now I want to use this method in a Task.Run (from my Windows Forms App,at button-click) which can be cancelled:

private CancellationTokenSource _ctSource;

try
            {
                Task.Run(() =>
                {
                    _worker.DoWork(_ctSource.Token);
                },_ctSource.Token);
            }
            catch (AggregateException aex)
            {
                String g = aex.Message;
            }
            catch (OperationCanceledException ex)
            {
                String g = ex.Message;
            }
            catch (Exception ex)
            {
                String g = ex.Message;
            }

但是当任务开始时,我无法用 _ctSource.Cancel();
我在visual studio中收到错误, OperationCanceledException 未被处理!

But when the task is started, I can't cancel it with _ctSource.Cancel(); I get an error in visual studio that the OperationCanceledException is not handled!

但是我在try-catch子句中包围了Task.Run调用!在 Worker 对象中出现的异常应该抛出异常?
有什么问题?

But I surrounded the Task.Run Call in a try-catch-clause! The Exception which ocurrs in the Worker object should thrown up or not? What is the problem?

推荐答案

您的 Task.Run 调用创建任务,然后立即返回。它不会抛出但是,创建的任务可能会在之后失败或被取消

Your Task.Run call creates the task and then returns immediately. It doesn't ever throw. But the task it creates may fail or be canceled later on.

您有几种解决方案:


  • 使用 await

await Task.Run(...)


  • 附加一个延续取决于失败/取消情况:

  • Attach a continuation depending on the failure/cancellation case:

    var task = Task.Run(...);
    task.ContinueWith(t => ..., TaskContinuationOptions.OnlyOnCanceled);
    task.ContinueWith(t => ..., TaskContinuationOptions.OnlyOnFaulted);
    


  • 在失败时附加一个延续:

  • Attach a single continuation on failure:

    Task.Run(...).ContinueWith(t => ..., TaskContinuationOptions.NotOnRanToCompletion);
    


  • 您可以/应该使用的解决方案取决于周围的代码。

    The solution you can/should use depends on the surrounding code.

    这篇关于在取消Task.Run时不会出现异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆