Reputation: 15112
I'm working on a Asp.Net 3.5 Web Application which requires Async Web service calls. Here is some code. I have written the code for Async calling using delegates but somehow my HttpContext.Current.Session is null. To make sure, I even tried passing HttpContext.
static HttpContext httpContext;
public void AsyncGetUser()
{
httpContext = HttpContext.Current;//not getting Session as null here
GetUserDelegate delegate = new GetUserDelegate(InvokeWrapperMethod);
IAsyncResult async = delegate.BeginInvoke(httpContext,new AsyncCallback(CallbackMethod), null);
}
static void CallbackMethod(IAsyncResult ar)
{
AsyncResult result = (AsyncResult)ar;
GetUserDelegate caller = (GetUserDelegate)result.AsyncDelegate;
caller.EndInvoke(ar);
}
private static void InvokeWrapperMethod(HttpContext hc)
{
HttpContext.Current = hc; //getting Session as null here
UserInfo userInfo = Service.GetUserInfo();
SetInSession(USER_INFO, userInfo);
}
I have tried <modules runAllManagedModulesForAllRequests="true">
and
<system.webServer>
<modules>
<remove name="Session"/>
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
</modules>
as this SO question suggested but didn't work. I would appreciate if you guys could give some pointers. Thanks.
Upvotes: 1
Views: 3192
Reputation: 45135
It might be that you're using delegates to get the 'handy' BeginInvoke method. This is inefficient since behind the scenes, its using a load of Reflection. If the background work is always significant then this overhead gets amortised, but its its sometimes just a few reads, then it'll take longer than doing it on the original thread.
You could install RX for 3.5 and use the 'mini TPL' to get at Tasks. This in itself could solve the problem (the issue might be the way in which that delegate.BeginInvoke is written), else try passing the context in as the state instance.
I know you've refactored out of the problem (probably a good thing) but I add this answer for completeness having looked more at what you were originally doing.
Upvotes: 0
Reputation: 45135
This can occur in ASP.NET apps using the async/await
(TAP) pattern. To solve this, you need to add this to your appSettings
section in web.config.
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
This may require .NET 4.5, I note you are not using this version but I add this answer here for others that have upgraded projects and are hitting this issue with their TAP code.
Upvotes: 1
Reputation: 15112
I ended up with the decision to refactor the whole project.
Upvotes: 0
Reputation: 4360
your web service should use , IRequiresSessionState
marker interface to enable session.
Upvotes: 0