c# - 任务的 OnCompleted 回调在哪里?

标签 c# callback async-await task

我希望能够做到这一点:

class MyClass
{
    IRepo repo;
    public MyClass(IMyRepo repo) { this.repo = repo; }

    long ID { get; set; }
    string Prop1 { get; set; }
    string Prop2 { get; set; }

    public async Task LoadAsync()
    {
        await Task.WhenAll(
            repo.GetProp1ByIDAsync(ID).OnComplete(x => Prop1 = x),
            repo.GetProp2ByIDAsync(ID).OnComplete(x => Prop2 = x)
        );
    }
}

当然,我似乎找不到任何标准库具有 TaskOnComplete 扩展。我真的需要创建自己的方法吗?或者是否有一个库已经有了这种扩展方法?我看到有 ContinueWith 但这并没有给我展开的结果,我仍然必须 await.Result 它......所以那不会阻塞线程吗?暂停第二次 repo 调用直到完成?如果它不能阻止它,那为什么我得到的结果仍然是包装的,将未包装的结果返回给我会更干净吗?还是我遗漏了什么?

最佳答案

I can't seem to find any standard library that has this OnComplete extension for Task. Do I really need to create my own or is there a library that already has this extension method? I see that there's ContinueWith but that does not give me the unwrapped result, I still have to await it or .Result it... so wouldn't that block the thread?

ContinueWith 是您正在寻找的方法; Result 不会阻塞任务,因为它在回调被调用时已经完成。

但是,ContinueWith 是一个危险的低级 API。您应该改用 await:

public async Task LoadAsync()
{
    await Task.WhenAll(
        LoadProp1Async(),
        LoadProp2Async()
    );
}

private async Task LoadProp1Async()
{
  Prop1 = await repo.GetProp1ByIDAsync(ID);
}

private async Task LoadProp2Async()
{
  Prop2 = await repo.GetProp2ByIDAsync(ID);
}

关于c# - 任务的 OnCompleted 回调在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39239295/

相关文章:

c# - TPL 数据流消费者一次处理多个项目

javascript - 在 javascript 中调用 C# 函数,它在页面加载之前执行。为什么?

javascript - 如何使用回调与 JavaScript 链接动画

javascript - 如何在 javascript 中对用户函数进行自定义回调

javascript - 异步函数不在 forEach 循环内等待

c# - Entity Framework 数据库优先 - Table per hierarchy (TPH) 递归关系实现

c# - ConfigurationProperty 的规范示例

单击按钮时未调用 JavaScript 回调

javascript - 使用 async wait 时 axios 不返回数据

c# - Task.WaitAll 不等待其他异步方法