【问题标题】:The IAsyncResult asynchronous pattern - TAP and REST API [closed]IAsyncResult 异步模式 - TAP 和 REST API [关闭]
【发布时间】:2014-01-15 17:08:50
【问题描述】:

我对 wcf 的以下 API/类有疑问。(http://blog.stephencleary.com/2012/08/async-wcf-today-and-tomorrow.html)

它暴露了基于基于任务的异步模式的 IAsyncResult 异步模式。这是一个正确的方法吗? 什么是回调? 什么是 REST API?(基于任务的 API?)

[DataContract]
public class CalculatorFault
{
  [DataMember]
  public string Message { get; set; }
}

[ServiceContract]
public interface ICalculator
{
  // Synchronous equivalent:
  //  [OperationContract]
  //  [FaultContract(typeof(CalculatorFault))]
  //  uint Divide(uint numerator, uint denominator);

  [OperationContract(AsyncPattern = true)]
  [FaultContract(typeof(CalculatorFault))]
  IAsyncResult BeginDivide(uint numerator, uint denominator, AsyncCallback callback, object state);
  uint EndDivide(IAsyncResult asyncResult);
}
public class Calculator : ICalculator
{
  public async Task<uint> DivideAsync(uint numerator, uint denominator)
  {
    try
    {
      var myTask = Task.Factory.StartNew(() => numerator / denominator);
      var result = await myTask;
      return result;
    }
    catch (DivideByZeroException)
    {
      throw new FaultException<CalculatorFault>(new CalculatorFault { Message = "Undefined result" });
    }
  }
public IAsyncResult BeginDivide(uint numerator, uint denominator, AsyncCallback callback, object state)
  {
    // See the Task-Based Asynchronous Pattern document for an explanation of the Begin/End implementations.
    var tcs = new TaskCompletionSource<uint>(state);
    var task = DivideAsync(numerator, denominator);
    task.ContinueWith(t =>
    {
      if (t.IsFaulted)
        tcs.TrySetException(t.Exception.InnerExceptions);
      else if (t.IsCanceled)
        tcs.TrySetCanceled();
      else
        tcs.TrySetResult(t.Result);

      if (callback != null)
        callback(tcs.Task);
    });

    return tcs.Task;
  }

  public uint EndDivide(IAsyncResult asyncResult)
  {
    try
    {
      return ((Task<uint>)asyncResult).Result;
    }
    catch (AggregateException ex)
    {
      // Note: the original stack trace is lost by this re-throw, but it doesn't really matter.
      throw ex.InnerException;
    }
  }

}

【问题讨论】:

  • 它来自stephen-cleary 我敢打赌这是对的。
  • @Harrison - 我明白了。将 Task 用于 IAsyncResult 看起来有点奇怪。我想了解它所基于的逻辑以及他为什么使用这种方法。以及什么是调用回到这里?还有 REST API?

标签: c# wcf rest asynchronous


【解决方案1】:

这是一个正确的方法吗?

是的,但不再需要了。那篇博文中的“今天”指的是 .NET 4.0,这是写博文时的最新版本(2012 年 8 月)。该博文中的“明天”指的是 .NET 4.5。

在现代 (.NET 4.5) WCF 服务器中,您可以只使用基于任务的 API,而忽略旧的 IAsyncResult 兼容性转换。

什么是回调?

当事情发生时调用的方法。

什么是 REST API?

具象状态传输,一个花哨的术语,本质上意味着您按照最初设计使用的方式使用 HTTP 协议。 WebAPI 是一个支持 ASP.NET 和自托管的现代 REST 友好框架。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多