gpt4 book ai didi

c# - System.Threading.Tasks -> 延续

转载 作者:行者123 更新时间:2023-11-30 12:12:47 26 4
gpt4 key购买 nike

假设您有服务:

interface ISuessService {
Task<Thing> Thing1();
Task<Thing> Thing2();
}

我有一个扩展方法 ContinueOnUIThread,我可以在其中做很酷的事情,例如:

myService.Thing1().ContinueOnUIThread(_ => label.Text = "Done!");

并轻松与 UI 线程交互。

实现执行此操作的新 ContinueWith 扩展方法的最佳方法是什么:

myService.Thing1()
.ContinueWith(myService.Thing2())
.ContinueOnUIThread(_ => label.Text = "Done!");

基本上在 Thing1 完成后启动 Thing2,然后调用 UI 线程。

我最接近的是这样的,但我真的不喜欢调用 Wait:

myService.Thing1()
.ContinueWith(_ => {
var thing2 = myService.Thing2().Wait();
return thing2.Result;
})
.ContinueOnUIThread(_ => label.Text = "Done!");

有没有一种干净的方法来做到这一点?

PS - 我没有 .Net 4.5,所以不允许等待/异步 - 此代码必须在 Android 的 MonoTouch/Mono 上运行,所以坚持使用 4.0

PS - 注意我使用了 _,这只是“我并没有真正使用这个参数”的快捷方式

最佳答案

我认为您可能正在寻找的是 Unwrap方法来自 System.Threading.Tasks.TaskExtensions

myService.Thing1()
.ContinueWith(_ => myService.Thing2()).Unwrap()
.ContinueOnUIThread(_ => label.Text = "Done!");

关于c# - System.Threading.Tasks -> 延续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12924122/

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