会话访问和异步回调

时间:2012-08-10 18:10:36

标签: c# asp.net-mvc session asynchronous delegates

好的,所以我在网站的登录页面上进行了一系列异步Web服务调用。我想将这些调用的结果设置为session,以便稍后可以使用它们,但我不能,因为HttpContext.Current在回调中为空。基本上,我想做这样的事情:

public ActionResult Something()
{
    GetLoans();              //each of these is async
    GetPartInfo();           //and sets its result to session
    GetOtherAsyncStuff();    //(or at least it needs to)
    //lots of other stuff
    Return View();
}

GetLoans()看起来像这样:

public IAsyncResult GetLoans()
{
    IAsyncResult _ar;
    GetLoansDelegate d_Loans = new GetLoansDelegate(GetLoansAsync);
    _ar = d_Loans.BeginInvoke(parameter1,parameter2, GetLoansCallback, new object()); //new object() is just a placeholder for the real parameters im putting there
    return _ar;
}

异步调用GetLoansAsync,其回调为GetLoansCallback(),如下所示:

private void GetLoansCallback(IAsyncResult ar)
{
    AsyncResult result = (AsyncResult)ar;
    GetLoansDelegate caller = (GetLoansDelegate)result.AsyncDelegate;
    List<Loan> loans = caller.EndInvoke(ar);

    Session["Loans"] = loans;   //this call blows up, since HttpContext.Current is null
}

我无法实现自定义会话提供程序,因此我必须坚持使用我所拥有的内容。因此,我无法在异步回调中为会话设置任何内容。有办法解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

您可以查看此博文。

http://blogs.msdn.com/b/tmarq/archive/2010/04/14/performing-asynchronous-work-or-tasks-in-asp-net-applications.aspx

基本上,它表示HttpContext在完成工作时无法使用(即在回调中),看起来你必须将会话操作移到GetLoansAsync方法中。