More async and task questions
Hi, I have a few questions about the async and the tpl and hope you guys could shed some light on it.
So, if I have an async method FooAsync() that returns Task<T> does that mean that all functions/methods that call my FooAsync() will need to be an async method as well? Let's say Duck() calls FooAsync() does that mean I have to rewrite Duck() into DuckAsync() that awaits FooAsyn()? Also will any method that calls Duck() need to be converted into their async version? Where does it end? And what is the proper way of using async in this method call chain?
My second question is, if I am working with an API that uses the old async pattern (Asynch Programming Model) does that mean I can't use the new async await mechanisms along with it?
Third, If I want a background thread that checks status and performs it's own utility process continuously alongside my main app would I use Task.Run() or any of the TPL or would creating a class that contains it's own thread field and static fields to manage the thread be better to serve my purpose?
9 comments · 74% upvoted · other discussions
Ideally, yes. The main benefit of
asyncis that it doesn't have to block a thread while waiting for something, if you wait on a task synchronously this benefit is largely lost. There is also a risk of deadlocks if your async method doesn't useConfigureAwait(false).There is a helper method for this purpose.
The docs look like a mess because it needs fairly flexible overloads, but you can look at some usage examples.
The reason why
Task.Runis discouraged for long running operations is because it uses the thread pool, which expects to get its thread back reasonably quickly and will hesitate to start new threads leading to potential scaling/performance problems. In practice, doing it once probably won't have any noticeable effect, though.[deleted] 3 points · Nov 2018
Actually there's a minor performance gain to having methods that simply return a task, simply return a task. Don't make them async at all. Otherwise you're spot on as usual :)
[deleted] 3 points · Nov 2018
But also benefits to not doing so: https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md#prefer-asyncawait-over-directly-returning-task
[deleted] 1 points · Nov 2018
Indeed :) As with everything, you do the right thing in the right situation as there's never a one size fits all solution.
Is this yours? The ConfigureAwait section is TBD. You can fill it in by saying (keeping in mind the above) use ConfigureAwait(false) for all the things :)
[deleted] 2 points · Nov 2018
Not mine, but David Fowlers, from the asp.net team. The guy who created SignalR. He knows async pretty well. 😉
[deleted] 1 points · Nov 2018
He does :) Did he do the first version of ASP.NET MVC too? It probably doesn't matter :)
[deleted] 2 points · Nov 2018
Worked some on it, as far as I can tell. https://www.linkedin.com/in/davidfowl