gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:34:25 25 4
gpt4 key购买 nike

我希望能够做到这一点:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com