Many awaits for Async method, or a single await for a wrapping Task.Run?

孤者浪人 提交于 2019-12-04 17:08:19

Your analysis is largely correct. You seem to overestimate the burden that this would place on the UI thread; the actual work that it would be asked to do is fairly small, so odds are that it would be able to keep up fine, but it's possible that you'd be doing enough that it couldn't, so you're right to be interested in not performing the continuations on the UI thread.

What you're missing of course is the preferred way of avoiding all of the call backs to the UI thread. When you await an operation, if you don't actually need the rest of the method to return back to the original context you can simply add ConfigureAwait(false) to the end of the task that you're awaiting. This will prevent the continuation from running in the current context (which is the UI thread) and instead let the continuation run in a thread pool thread.

Using ConfigureAwait(false) allows you to avoid the UI being responsible for non-UI work unnecessarily while also preventing you from needing to schedule thread pool threads to do more work than they need to do.

Of course, if the work that you end up doing after your continuation is actually going to do UI work, then that method shouldn't be using ConfigureAwait(false);, because it actually wants to schedule the continuation on the UI thread.

This all depends on what the UI is expecting. If the UI depends on the operation being complete in order to retain a valid state then you have no choice but to wait for the async task or use a call on the main UI thread as you would normally.

Threading is great for tasks that take a long time but are NOT required by the calling thread immediately or the calling thread is dependant on the result of the operation.

Tasks are no there to speed things up, they are there for efficiency. So you could keep the task thread and raise an event with an 'operation completed' leaving the UI to operate normally while this operation is happening, but like I said if the UI thread depends on the result, you have no choice but to wait.

If you go via the event route, you can update your UI asynchronously with the results as they come in

There is one important difference between the two solutions. The first one is single-threaded (unless you use ConfigureAwait(false) as suggested by @Servy), while the second one is multi-threaded.

Multi-threadedness always introduces extra complexity to your program. You should start by asking yourself if you're willing to trade that for the benefits you might gain.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!