[英]Asynchronous methods and asynchronous delegates
C# 3.0 in a nutshell says asynchronous methods and asynchronous delegates looks similar but the behavior is very different. 简而言之,C#3.0说异步方法和异步委托看起来很相似,但行为却截然不同。
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. 当我通过反射器查看System.IO.Stream类中的BeginRead()方法时,它正在使用委托并在其上调用BeginInvoke 。 So an asynchronous method is using an asynchronous delegate internally.
因此异步方法在内部使用异步委托。
Any thoughts? 有什么想法吗?
At the core, there are two main behaviors you may see when you call BeginFoo() with a callback. 在核心,当您使用回调调用BeginFoo()时,您可能会看到两个主要行为。
When you use a delegate, behavior #1 above happens. 当您使用委托时,会发生上述行为#1。
Some APIs (that have underlying support for non-blocking IO calls) support behavior #2. 某些API(具有对非阻塞IO调用的底层支持)支持行为#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. 在'Stream'的特定情况下,我不确定,但我的猜测是它是一个抽象基类,所以这只是一个只实现Read同步版本的子类的默认行为。 A 'good' subclass would override BeginRead/EndRead to have a non-blocking implementation.
'good'子类将覆盖BeginRead / EndRead以具有非阻塞实现。
The advantage of #2, as you said, is that you can have eg 100 pending IO calls without consuming 100 threads (threads are expensive). 正如你所说,#2的优势在于你可以拥有100个待处理的IO调用而不需要消耗100个线程(线程很昂贵)。
BackgroundWorker
, ThreadPool.QueueUserWorkItem
, or Parallel.For
(etc) in .NET 4.0 BackgroundWorker
, ThreadPool.QueueUserWorkItem
或Parallel.For
(etc) I think what the book is trying to highlight is that delegates always include this pattern: 我想这本书试图强调的是代表们总是包含这种模式:
Invoke
) that can block Invoke
) BeginInvoke
) that shouldn't really block unless the thread-pool is saturated BeginInvoke
) but 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. 最近(例如,Silverlight或
WebClient
的异步IO方法):而不是IAsyncResult
,事件用于表示完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.