Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# .NET, does an async operation necessarily create a thread that blocks?

This is more of a general question regarding the asynchronous patterns in C# .NET described on MSDN here.

When a long running synchronous operation is required to be called (eg - WCF, DB query, IO, etc), and I don't want the thread to block (eg - GUI thread), does this mean that there must exist another thread somewhere that does the blocking?

Does making a synchronous call asynchronous necessarily require a thread somewhere to block?

So, if I make 10 long-running async calls (which are actually 10 synchronous calls), must there be 10 threads out there doing the waiting? Or is there a mechanism to prevent 10 threads from being blocked?

In WCF, you can create Begin and End methods for a WCF call to make it asynchronous. Does this mean that when I call this asynchronous method, there is a thread somewhere, either on the client or the server, that does the waiting for me?

I have read several articles about varying methods to achieve asynchrony, but these articles don't explain what is done under the hood.

Update

I made my question more specifc, since I'm more about interested in the .NET. async patterns described by MSDN.

Update 2

I reformed the question to be even more specific to making synchronous calls asynchronous.

like image 277
Mas Avatar asked Mar 06 '12 10:03

Mas


3 Answers

In .NET Framework, there are many ways to implement an asynchronous operation: by using thread, thread pool, BeginXxx and EndXxx methods, event based APM, or Task based APM.

Each async pattern has its own internal implementation and all these Asynchronous Programming Models are explained at this blog article, including the traditional BeginXxx and EndXxx async pattern.

Below is the Summary of all the Async Patterns for quick reference: Async Summary:

Moreover, Jeffrey Richter also explains the CLR Asynchronous Programming Model in MSDN Magazine nicely.

like image 162
VSS Avatar answered Oct 27 '22 16:10

VSS


It's not necessarily one thread per operation. As @Ioannis Karadimas, says, this most likely depends on the implementation.

For example, imagine I want to do async receives from 10 different sockets. This can be accomplished with a single extra thread using a call to select in a loop, which non-deterministically selects one available socket when a message is received.

like image 40
Tudor Avatar answered Oct 27 '22 16:10

Tudor


Unfortunately, there is no single answer to this. Some libraries provide natively implemented asynchronous operations, like sockets for instance, in which it's supported by the hardware. Others might not, like a third - party library that might very well block.

like image 38
Ioannis Karadimas Avatar answered Oct 27 '22 15:10

Ioannis Karadimas