Reputation: 15521
C# 3.0 in a nutshell says asynchronous methods and asynchronous delegates looks similar but the behavior is very different.
Here is what the book says about both.
The book also says, The purpose of asynchronous methods is to allow many tasks to run on few threads; the purpose of asynchronous delegates is to execute a task in parallel with the caller.
When I looked into the BeginRead() method in System.IO.Stream class through reflector, it is using a delegate and calling BeginInvoke on that. So an asynchronous method is using an asynchronous delegate internally.
Any thoughts?
Upvotes: 11
Views: 4739
Reputation: 1064014
BackgroundWorker
, ThreadPool.QueueUserWorkItem
, or Parallel.For
(etc) in .NET 4.0I think what the book is trying to highlight is that delegates always include this pattern:
Invoke
) that can blockBeginInvoke
) that shouldn't really block unless the thread-pool is saturatedbut it isn't the only pattern. Also; more recently (for example, the async IO methods in Silverlight, or in WebClient
): rather than an IAsyncResult
, an event is used to signal completion.
Upvotes: 5
Reputation: 118905
At the core, there are two main behaviors you may see when you call BeginFoo() with a callback.
When you use a delegate, behavior #1 above happens.
Some APIs (that have underlying support for non-blocking IO calls) support behavior #2.
In the specific case of 'Stream', I am not sure, but my guess is it is an abstract base class and so this is merely the default behavior for a subclass that implements only a synchronous version of Read. A 'good' subclass would override BeginRead/EndRead to have a non-blocking implementation.
The advantage of #2, as you said, is that you can have e.g. 100 pending IO calls without consuming 100 threads (threads are expensive).
Upvotes: 7