Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use ConfigureAwait(false) when awaiting IAsyncAction?

It is recommended e.g. here to use ConfigureAwait(false) as much as possible on awaited tasks.

Does this recommendation also extend to methods that return IAsyncAction, for example StreamSocket.ConnectAsync()?

That is, instead of simply writing this in my class library:

await socket.ConnectAsync(hostName, port);

I should rather write this?

await socket.ConnectAsync(hostName, port).AsTask().ConfigureAwait(false);
like image 300
Anders Gustafsson Avatar asked Nov 02 '15 11:11

Anders Gustafsson


People also ask

When should I use ConfigureAwait?

A situation to use ConfigureAwait(true) is when performing await in a lock, or using any other context/thread specific resources. This requires a synchronization context, which you will have to create, unless you are using Windows Forms or WPF, which automatically create a UI synchronization context.

Is it OK to use ConfigureAwait false only on the first await in my method and not on the rest?

Is it ok to use ConfigureAwait(false) only on the first await in my method and not on the rest? In general, no. See the previous FAQ. If the await task.

Should I use ConfigureAwait false everywhere?

As a general rule, ConfigureAwait(false) should be used for every await unless the method needs its context. It's even what Stephen Cleary (a Microsoft MVP) says in his Async and Await article: A good rule of thumb is to use ConfigureAwait(false) unless you know you do need the context.


1 Answers

Yes. It's a best practice to have any method that does not need its context, use ConfigureAwait(false). The configuring is for the await (not the Task or IAsyncAction), and there is an await there that should be configured.

like image 99
Stephen Cleary Avatar answered Oct 25 '22 14:10

Stephen Cleary