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?