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?
An asynchronous delegate is a delegate that you call, and it returns a Task of some kind. It's not the call that's asynchronous - it's the processing within the delegate.
An async method runs synchronously until it reaches its first await expression, at which point the method is suspended until the awaited task is complete. In the meantime, control returns to the caller of the method, as the example in the next section shows.
Delegates enable you to call a synchronous method in an asynchronous manner. When you call a delegate synchronously, the Invoke method calls the target method directly on the current thread. If the BeginInvoke method is called, the common language runtime (CLR) queues the request and returns immediately to the caller.
Synchronization means two or more operations happen sequentially. Asynchronous means two or more operations are running in different contexts (thread) so that they can run concurrently and do not block each other.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With