【问题标题】:Why does the IHttpAsyncHandler provide extraData parameter?为什么 IHttpAsyncHandler 提供 extraData 参数?
【发布时间】:2015-09-25 11:37:38
【问题描述】:

与今天的技术有点不相关,但我 saw another way of working 使用 APM 环境中的任务,除了 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 并使用该数据。

那么为什么会出现呢?

【问题讨论】:

    标签: c# asp.net asynchronous


    【解决方案1】:

    简而言之,APM Pattern 需要它,IHttpAsyncHandler 正在关注它。您在这里不需要它,但在某些情况下(模式使用,而不是处理程序使用)关联回调很有用。

    更新:

    这是在 APM 中使用 Tasks 的 recommended way

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

    请注意,状态是传递给任务工厂,结果任务既作为回调的参数,又作为返回值。

    【讨论】:

    • 是的,我是这么认为的/只是想确定一下。它只是想成为一个优秀的 APM 公民。因此它遵循协议。但它实际上什么都不做
    • 不过,别忘了把它传递给IAsyncResult.AsyncState
    • 我猜你的意思是说“当你没有任何状态时”——但如果我这样做了——那么I already doing it via the TCS
    • 不,我的意思是“总是”。您应该将AsyncState 设置为BeginXXX 最后一个参数的值。
    猜你喜欢
    • 2014-04-08
    • 2016-04-24
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    相关资源
    最近更新 更多