DEV Community

Cover image for Random Facts: Async Programming in .NET
Mukund Raghav Sharma (Moko)
Mukund Raghav Sharma (Moko)

Posted on

Random Facts: Async Programming in .NET

This post aggregates random tidbits and their sources to pick up on a couple of Async Programming Concepts. I did a deep dive whose notes can be found here.

ConfigureAwait

General rule of thumb, use ConfigureAwait(false) while awaiting a task if the control doesn’t need to go to the original captured context. Without ConfigureAwait(false), the next steps are posted on the original captured context i.e. SynchronizationContext.Post(..). This can also reduce impact on the UI thread and prevent deadlock conditions.

“As a general rule, every piece of code that is not in a view model and/or that does not need to go back on the main thread should use ConfigureAwait false.”

Good references:

  1. https://johnthiriet.com/configure-await/
  2. https://channel9.msdn.com/Series/Three-Essential-Tips-for-Async/Async-library-methods-should-consider-using-Task-ConfigureAwait-false-

Thread Affinity

Thread that instantiates the object is the only thread that is allowed to access and mutate the members.

Good reference:
https://www.linkedin.com/learning/advanced-threading-in-c-sharp/thread-affinity?u=3322

AutoResetEvent vs. ManualResetEvent

Thread-safe signaling mechanism where WaitOne(): Blocks the current thread until the EventWaitHandle sends the signal of Set().

The difference between a tollbooth and a door. The ManualResetEvent is the door, which needs to be closed (reset) manually. The AutoResetEvent is a tollbooth, allowing one car to go by and automatically closing before the next one can get through.

Good Reference:
https://stackoverflow.com/questions/153877/what-is-the-difference-between-manualresetevent-and-autoresetevent-in-net

CountdownEvent

IDisposable synchronization primitive that signals when the count reaches 0. Signal() decrements the count and the threads that are blocked via Wait() are released when the count = 0.

TaskCompletionSource

TaskCompletionSource is a class which wraps a Task whose state we can manually control.

Good References:

  1. http://www.levibotelho.com/development/async-processes-with-taskcompletionsource/
  2. Use Case: https://stackoverflow.com/questions/15316613/when-should-taskcompletionsourcet-be-used

IO vs. CPU Bound and Async Programming in CSharp

For I/O-bound code, you await an operation which returns a Task or Task<T> inside of an async method.
For CPU-bound code, you await an operation which is started on a background thread with the Task.Run method.

Background Threads

The background threads will stop executing when it either finishes executing the delegate, or when there are no more foreground threads in the entire process i.e. the process will disallow the continuation of the background thread execution if the foreground threads have reached the end of the process.

Discussion (0)