与今天的技术不相关,但我在APM环境中使用http://i.imgur.com/2LHERrg.png,除了Task.FromAsync
asp.net中的异步处理程序:
public class Handler : IHttpAsyncHandler
{
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
//...
}
public void EndProcessRequest(IAsyncResult result)
{
//...
}
}context参数是我可以访问/(或传递给另一个beginXXX操作)请求和响应的实际上下文。cb是在操作完成后执行/(或传递给另一个beginXXX操作)。问题
但是object extraData在方法的签名中做了什么呢?
这并不是说我从框架中获得了某种状态,相反,我创建了状态并将其传递给它,这样我的EndXXX就可以将result.AsyncState转换为T并使用这些数据。
那它为什么在那里?
发布于 2015-09-25 11:54:51
简单地说,它是APM模式所要求的,IHttpAsyncHandler也是这样做的。在这里您不需要它,但是有一些情况(模式使用,而不是处理程序使用)是有用的,可以将回调关联起来。
更新:
public IAsyncResult BeginCalculate(int decimalPlaces, AsyncCallback ac, object state)
{
Console.WriteLine("Calling BeginCalculate on thread {0}", Thread.CurrentThread.ManagedThreadId);
Task<string> f = Task<string>.Factory.StartNew(_ => Compute(decimalPlaces), state);
if (ac != null) f.ContinueWith((res) => ac(f));
return f;
}
public string Compute(int numPlaces)
{
Console.WriteLine("Calling compute on thread {0}", Thread.CurrentThread.ManagedThreadId);
// Simulating some heavy work.
Thread.SpinWait(500000000);
// Actual implemenation left as exercise for the reader.
// Several examples are available on the Web.
return "3.14159265358979323846264338327950288";
}
public string EndCalculate(IAsyncResult ar)
{
Console.WriteLine("Calling EndCalculate on thread {0}", Thread.CurrentThread.ManagedThreadId);
return ((Task<string>)ar).Result;
}请注意,状态传递给任务工厂,并将结果任务用作回调和返回值的参数。
https://stackoverflow.com/questions/32781332
复制相似问题