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 · 90% upvoted · other discussions
If you want to reap the benefits of async code, you need async all the way to the top. C# 7.1 allows an async main, so there's no reason not to. Of course, if you're doing a GUI desktop app there's a lot of care to be taken around thread contexts, but that's a separate issue.
It's fairly easy to wrap old callback-based async code. What you'll want to look at is the TaskCompletionSource.
Whether you run the task from it's own class or not, does not matter a lot, I think (I personally prefer to push status updates from the worker process). If it's going to be long-lived, make sure to use the appropriate flags. Consult David Fowlers excellent list to make sure you aren't falling into any less-than-obvious traps.