C# 会话访问和异步回调
好的,我在我的网站的登录页上进行了一系列异步web服务调用。我想将这些调用的结果设置为session,以便以后可以使用它们,但我不能,因为C# 会话访问和异步回调,c#,asp.net-mvc,session,asynchronous,delegates,C#,Asp.net Mvc,Session,Asynchronous,Delegates,好的,我在我的网站的登录页上进行了一系列异步web服务调用。我想将这些调用的结果设置为session,以便以后可以使用它们,但我不能,因为HttpContext.Current在回调中为null。基本上,我想这样做: public ActionResult Something() { GetLoans(); //each of these is async GetPartInfo(); //and sets its result to
HttpContext.Current
在回调中为null。基本上,我想这样做:
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();
}
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;
}
其中GetLoans()
如下所示:
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();
}
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
}
private void GetLoansCallback(IAsyncResult ar)
{
AsyncResult=(AsyncResult)ar;
GetLoansDelegate调用程序=(GetLoansDelegate)result.AsyncDelegate;
List loans=caller.EndInvoke(ar);
Session[“Loans”]=Loans;//由于HttpContext.Current为null,因此此调用中断
}
我无法实现自定义会话提供程序,因此我必须坚持使用现有的会话提供程序。因此,就目前情况而言,我无法在异步回调中为会话设置任何内容。有没有办法绕过这个问题 你可以看看这个
基本上,它说,
HttpContext
在工作完成时(即在回调中)不可用,看起来您必须将会话操作移动到GetLoansAsync
方法中。您可以创建自己的会话(静态字典),然后在其中设置结果。确保您对该数据结构的访问是线程安全的。@Stefan是的,我考虑过了。现在,我正在尝试在控制器级别声明几个变量,并将它们设置为异步调用的结果,然后在使用异步等待句柄的WaitOne()
方法后,将它们设置为在UI线程上返回会话。我会让您知道goesI是如何相信静态对象在所有客户端之间是共享的,而不是每个客户端所特有的会话。如果包含的数据不应该在用户之间共享,我不鼓励使用静态对象。@user1121108如果我提供了任何混淆,很抱歉。是的,静态对象在应用程序域中共享,它们需要是线程安全的。我所说的“创建您自己的会话”是指您需要使用一个用户密钥(可能将其存储在实际会话中)来存储每个用户的数据。@Stefan是的,现在明白了。事实上,这看起来是个好主意。