首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么IHttpAsyncHandler提供extraData参数?

为什么IHttpAsyncHandler提供extraData参数?
EN

Stack Overflow用户
提问于 2015-09-25 11:37:38
回答 1查看 299关注 0票数 0

与今天的技术不相关,但我在APM环境中使用http://i.imgur.com/2LHERrg.png,除了Task.FromAsync

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

代码语言:javascript
复制
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并使用这些数据。

那它为什么在那里?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-25 11:54:51

简单地说,它是APM模式所要求的,IHttpAsyncHandler也是这样做的。在这里您不需要它,但是有一些情况(模式使用,而不是处理程序使用)是有用的,可以将回调关联起来。

更新:

下面是在APM中使用推荐方式 s的推荐方式

代码语言:javascript
复制
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;
}

请注意,状态传递给任务工厂,并将结果任务用作回调和返回值的参数。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32781332

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档