4

I have an Asp.Net application that calls some WCF service using a proxy generated by svcutil. The generated proxy has async methods in the APM pattern (BeginXxx, EndXxx).

I am using the async targeting pack in order to leverage the new async/await pattern, and my target platform is .net 4.0 (otherwise I wouldn't have to use the async targeting pack).

I am using Task<T>.Factory.FromAsync to convert the APM pattern into a Task that I can await.

my code looks a little something like that (assuming the service method takes no parameters and returns an int:

int result = await Task<int>.Factory.FromAsync(proxy.BeginXxx, proxy.EndXxx, state: null);
HttpContext.Current.Items["reuslt"] = result;

The second line throws a NullReferenceException.

I am assuming that the reason is that the callback (which is everything that's running after the await call) does not have the original synchronization context.

other methods (like Factory.StartNew) have overloads that receive a TaskScheduler that can be used to preserve the context.

The FromAsync Method also has overloads that receive a TaskScheduler, but none that have the begin method as an argument.

Assuming I do not want to start passing the Http context by hand as a method argument to all methods that get called after this line, how do I use the overload that gets a task scheduler or otherwise get .Net to respect my synchronization context?

rony l
  • 5,798
  • 5
  • 35
  • 56

1 Answers1

5

I suspect the problem is actually in the ASP.NET pipeline, not in the SynchronizationContext.

The Async Targeting Pack enables async/await support, but there were a lot of changes in ASP.NET 4.5 to make it async-friendly, and the Targeting Pack doesn't include that support.

Try helping out the ASP.NET pipeline by using RegisterAsyncTask (for web forms) or AsyncManager (for MVC). Even then, there are some places in the pipeline that just can't take asynchronous code (still true in ASP.NET 4.5, but at least 4.5 will detect this and throw an error).

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • So I tried to use the overload that receives a scheduler, with no avail. Seems like your analysis is correct. I ended obtaining HttpContext.Current in the beginning of the flow (while it is still not null) passing it around through the rest of the flow. – rony l Aug 22 '12 at 01:23
  • Any tips for webapi in IIS and with .net 4.5. It behaves the same as for @ronyl – Konstantin Mar 06 '14 at 21:41