Monday, June 8, 2009

Spawning Threads / Delegates to Make Synchronous Calls

Spawning Threads to Make Synchronous Calls


There is another option available for solving many of the problems that asynchronous calls address. That is to simply spawn a thread and have that thread make easy-to-code synchronous calls. This may make sense in some scenarios, but you should realize a couple of issues with this approach.

First of all, this may make your Web service call code a little simpler, but there is a good chance that you will have to implement logic that is at least as complicated as some of the code we have used in order to manage and communicate between your threads. If you are making a lot of Web service calls, you may be overburdening your system with threads to manage. For a normal client application, this may not be a big deal, but if you are making calls from an ASP.NET page, you need to take into account how many users may simultaneously use your system. Adding two threads that do Web service calls from an ASP.NET page may not seem like a lot of overhead, but what happens if 200 other people are simultaneously using the same page? Now you are talking about 400 new threads, which is definitely significant. Although the callback mechanism for doing asynchronous calls uses extra threads for making the callbacks, they reuse a pool of threads in order to make the callbacks as efficient as possible—as well as to avoid problems with having hundreds of threads simultaneously running.


Spawning Delegates to Make Synchronous Calls


If spawning background threads to make your Web service calls still makes sense to you, then you should consider spawning these threads using delegates and the process thread pool. You can then call these methods using asynchronous paradigms similar to the ones we used for Web service callbacks and invoking function calls to interact with controls across threads. For more information on using delegates to make general asynchronous method calls, see Richard Grimes' article, .Net Delegates: Making Asynchronous Method Calls in the .Net Environment.


One of the most valuable aspects of asynchronous execution using delegates is that you don't have to worry about creating and managing secondary threads. The CLR automatically maintains a pool of worker threads for you, which means you can benefit from techniques involving asynchronous and parallel method execution without ever having to program directly against threads. All that remains to be learned is how to call BeginInvoke and End Invoke at the right times.


Thanks & Regards,

Arun Manglick || Senior Tech Lead



No comments:

Post a Comment