Labels

Monday, June 15, 2009

Threading || Asynchronous Delegates Over Asynchronous Methods

Asynchronous Methods

 

Asynchronous Delegates is one approach of Thread Pooling, out of the three approaches. Similar to the Asynchronous Delegates, there is another similar concept – Asynchronous Methods.

 

Some types in the .NET Framework offer asynchronous versions of their methods, with names starting with "Begin" and "End". These are called asynchronous methods and have signatures similar to those of asynchronous delegates.

 

Asynchronous Methods exist to solve a much harder problem: To Allow More Concurrent Activities Than You Have Threads.

For e.g. A web or TCP sockets server, for instance, can process several hundred concurrent requests on just a handful of pooled threads if written using NetworkStream.BeginRead and NetworkStream.BeginWrite.

 

Despite of the mentioned advantage, unless you're writing a high concurrency application, you should avoid asynchronous methods for a number of reasons:

 

· Unlike asynchronous delegates, asynchronous methods may not actually execute in parallel with the caller.

· The benefits of asynchronous methods erodes or disappears if you fail to follow the pattern carefully.

· Things can get complex pretty quickly when you do follow the pattern correctly.

 

However, if you really require the parallel execution, then better you go for the below alternatives –

 

  • Calling the synchronous version of the method (e.g. NetworkStream.Read) via an Asynchronous Delegate.
  • Another option is to use ThreadPool.QueueUserWorkItem or BackgroundWorker—or simply create a new thread.

 

 

Hope this helps.

 

Thanks & Regards,

Arun Manglick || Senior Tech Lead

 

 

No comments:

Post a Comment