简体   繁体   English

为什么IHttpAsyncHandler提供extraData参数?

[英]Why does the IHttpAsyncHandler provide extraData parameter?

A bit not relevant for today's technology but I saw another way of working with Tasks in APM environment , besides the Task.FromAsync 与当今的技术无关,但是我看到了除了Task.FromAsync之外,在APM环境中使用Tasks的另一种方法。

Async Handler in asp.net : asp.net中的异步处理程序:

public class Handler : IHttpAsyncHandler
{

 public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
    {
      //...
    }

    public void EndProcessRequest(IAsyncResult result)
    {
     //...
    }
  }
  • The context parameter is the actual context which I can access / (or pass to another beginXXX operation) request and response. context参数是我可以访问/ (或传递到另一个beginXXX操作)请求和响应的实际上下文。
  • cb is for me to execute / (or pass to another beginXXX operation) when the operation finished. cb对我来说是在操作完成时执行/ (或传递给另一个beginXXX操作)。

Question

But what is the object extraData is doing in the signature of the method ? 但是,方法的签名中的object extraData正在做什么?

It is not that I get some state from the framework , on the contrary - I create state and pass it forward so that my EndXXX could cast result.AsyncState to T and use that data. 相反, 不是从框架中获取某些状态,而是创建状态并将其传递给我,以便EndXXX可以将result.AsyncState为T并使用该数据。

So why is it there? 那为什么在那儿呢?

In short, it is required by the APM Pattern , which IHttpAsyncHandler is following. 简而言之, IHttpAsyncHandler遵循的APM模式是必需的。 You don't need it here, but there are cases (of pattern usage, not handler usage) when it is useful to correlate callbacks. 您在这里不需要它,但是在某些情况下(模式使用,而不是处理程序使用)关联回调很有用。

Update: 更新:

Here's the recommended way to use Task s in APM: 这是在APM中使用Task推荐方法

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;
}

Please note that the state is passes to task factory, and the resulted task is used as both the argument to the callback and the return value. 请注意,状态已传递给任务工厂,结果任务既用作回调的参数,又用作返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM