I am attempting to implement some async code in my Application. I start a new Task and dont wait for the results. This task that has been started news up another Task which does await the result. The second Task uses Http.Context (as I need to get the User from the http context) as the secondary Tasks which I wait on fires off an API call which uses the http.context.current.user.
I was using this answer in order to pass the current context into the Task.
So my code is as below:
var context = HttpContext.Current;
Task.Factory.StartNew(() =>
{
HttpContext.Current = context;
ExecuteMethodAndContinue();
});
private static void ExecuteMethodAndContinue()
{
var myService = ServiceManager.GetMyService();
var query = GetQuery();
var files = myService.GetFiles(query).ToList();
//Remaining code removed for brevity
}
The implementation of GetFiles which is called from other places in the code as well is as below:
public IDictionary<FileName, FileDetails> GetFiles(MyQuery query)
{
var countries = GetAllCountries();
var context = HttpContext.Current;
var taskList = countries.Select(c => Task.Factory.StartNew(() =>
{
HttpContext.Current = context;
return new Dictionary<FileName, FileDetails> { { c, GetFilesInCountry(query, c) } };
})).ToList();
try
{
// Wait on all queries completing
Task.WaitAll(taskList.ToArray<Task>());
}
catch (AggregateException ae)
{
throw new ApplicationException("Failed.", ae);
}
// Return collated results
return taskList.SelectMany(t => t.Result).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
}
The GetFilesInCountry method that actually contains the API call which relies on the Http.Context.Current.User. However when I hit a breakpoint on the return new line in GetFiles I can see the http.current.context.user is correctly set as expected. When I breakpoint into the GetFilesInCountry method if I hover over the Http.Context.Current.User in GetFiles I find that it is null.
I think this is due to the fact that the http request from where I started the first call (ExecuteMethodAndContinue) is finished so this is why the User on the current context is null.
Is there something straight forward I can do to correctly work around this?