问题描述
我一直在试图弄清为什么UI阻止了ViewModel方法,并意识到这部分代码:
I've been trying to figure out why the UI was blocking from a ViewModel method, and realized that this part of the code:
await Task.WhenAll(getOutput1(), getOutput2());
是问题所在.我设法使用以下方法解除了对用户界面的封锁:
was the problem. I managed to unblock the UI by using:
await Task.WhenAll(Task.Run(() => getOutput1()), Task.Run(() => getOutput2()));
在ViewModel中,
getOutput1()
和getOutput2()
都是async
,返回类型为Task
,并且从View调用了代码.
getOutput1()
and getOutput2()
are both async
with Task
return types in the ViewModel, and the code is called from the View.
当我调用Task.Run()并直接提供任务时,调用Task.WhenAll有什么区别?
What's the difference with calling Task.WhenAll when I call Task.Run() and just directly supplying the task?
推荐答案
直接调用方法将在UI线程上调用它们.从Task.Run
内部调用它们将在线程池线程上调用它们.
Calling the methods directly will invoke them on the UI thread. Calling them from within Task.Run
will invoke them on a thread pool thread.
结论:getOutput1
和/或getOutput2
实际上不是异步的. (一种方法完全有可能返回Task
-因此出现异步-但实际上只是同步阻塞).
Conclusion: getOutput1
and/or getOutput2
are not actually asynchronous. (It is entirely possible for a method to return Task
- and thus appear asynchronous - but in reality just block synchronously).
这篇关于Task.WhenAll(Task.Run(async方法))和Task.WhenAll(async方法)之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!