【问题标题】:Cancel ContinueWith Task chain and report error to caller取消ContinueWith任务链并向调用者报错
【发布时间】:2014-11-20 16:10:39
【问题描述】:

如果我有一个需要执行多个任务的“登录”命令,并且我的代码如下所示

public async void LoginAsync()
{
    await someService.Connect().ContinueWith(async (r) =>
    {
        //do some stuff with r.Result here
    })
    .ContinueWith(async (r) =>
    {
       //do some other stuff here
    })
    ContinueWith(async (r) =>
    {
       //do even more stuff here
    });

沿着幸福的道路前进,代码按预期执行,一切都很好。

我的问题是,如果链中的一个任务出现问题/异常,我该如何取消剩余的任务并向调用者报告问题所在?

我已经尝试在 ContinueWith 语句中抛出异常,但这些没有被我放在调用者代码周围的 try/catch 块捕获。

我已经阅读了关于 CancellationTokenSource 的信息,感觉它走在了正确的轨道上,但是尝试在这种情况下实现 MSDN 上的示例代码似乎行不通。

任何指针都会很棒

克里斯

【问题讨论】:

    标签: c# c#-4.0 task-parallel-library async-await windows-phone-8.1


    【解决方案1】:

    这里根本不要使用ContinueWithawait 每个 Task 你想创建一个延续,因为这会给你想要的错误处理语义。

    public async Task LoginAsync()
    {
        var result = await someService.Connect();
        //do some stuff with r.Result here
        //do some other stuff here
        //do even more stuff here
    }
    

    另外请注意,这样的方法应该返回一个Task,让调用者既可以知道操作何时完成,也可以确定它是否成功完成,如果它出错,则可以查看异常。

    【讨论】:

    • 完美。非常感谢
    猜你喜欢
    • 2018-02-02
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多