本文介绍了异步编程APM VS EAP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是真正的异步编程模型基于事件的格局台异步差异

该方法的使用是什么时候?

Which approach to use and when?

推荐答案

异步编程模型的( APM )是您与看到模型BeginMethod(...) EndMethod(...)对。

例如下面是一个插槽使用的 APM 执行:

For example here is a Socket using the APM implementation:

 var socket = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);

 // ...

 socket.BeginReceive(recvBuffer, 0, recvBuffer.Length,
                     SocketFlags.None, ReceiveCallback, null);

 void ReceiveCallback(IAsyncResult result)
 {
   var bytesReceived = socket.EndReceive(result);

   if (bytesReceived > 0) { // Handle received data here. }

   if (socket.Connected)
   {
     // Keep receiving more data...
     socket.BeginReceive(recvBuffer, 0, recvBuffer.Length,
                         SocketFlags.None, ReceiveCallback, null);
   }
 }

基于事件的异步模式的( EAP )是您与看到模型MethodAsync(...) CancelAsync(...)对。通常有一种已完成事件。 的BackgroundWorker 就是这种模式的一个很好的例子。

The Event-based Asynchronous Pattern (EAP) is the model you see with MethodAsync(...) and CancelAsync(...) pairs. There's usually a Completed event. BackgroundWorker is a good example of this pattern.

作为的 C#4.5 的,两人都被替换为异步/计谋模式,这是使用的任务并行库太平人寿)。你会看到他们打上异步 awaitable 工作任务< TResult> 。如果你能够针对.NET 4.5,你绝对应该使用这种模式在APM或EAP设计。

As of C# 4.5, both have been replaced by the async/await pattern, which is using the Task Parallelism Library (TPL). You will see them marked with Async after the method name and usually returning an awaitable Task or Task<TResult>. If you are able to target .NET 4.5, you should definitely use this pattern over the APM or EAP design.

例如,COM pressing(潜在大)文件异步:

For example, compressing a (potentially large) file asynchronously:

public static async Task CompressFileAsync(string inputFile, string outputFile)
{
  using (var inputStream = File.Open(inputFile, FileMode.Open, FileAccess.Read))
  using (var outputStream = File.Create(outputFile))
  using (var deflateStream = new DeflateStream(outputStream, CompressionMode.Compress))
  {
    await inputStream.CopyToAsync(deflateStream);

    deflateStream.Close();
    outputStream.Close();
    inputStream.Close();
  }
}

这篇关于异步编程APM VS EAP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 08:19