Posts

Showing posts from October, 2017

The Async/Void Trap

Image
Example Code I’ll start by saying, you should ALWAYS avoid async/void. Now, I’m sure there are edge cases, but the reality is you can get into a lot of trouble with async/void. A good  article in MSDN Magazine  goes over some best practices when using async/await and asynchronous programming patterns. As the article points out, avoid async/void. However, it also states that an exception to that rule is event handlers where the delegate returns void. Even with those event handlers, you need to be extremely careful. Here’s why–await is actually not blocking. I know if feels like it is, but remember, async/await is just syntax sugar for ContinueWith() and context management. Let’s look at some code. Take some method Foo() that returns void and calls an async method Bar() async void Foo () { await Bar (); } Task Bar () { return Task . Delay ( 10000 ); } Now, if we call Foo(), it will return immediately, and Bar() will be executed in backgrou...