【发布时间】: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