In my ASP.NET 5 app, I want to load some data from Azure into a cache inside my Startup.Configure method. The Azure SDK exposes async methods exclusively. Typically, calling an async method is done via await inside an async method, like this:
public async Task Configure(IApplicationBuilder app, IMemoryCache cache)
{
Data dataToCache = await DataSource.LoadDataAsync();
cache.Set("somekey", dataToCache);
// remainder of Configure method omitted for clarity
}
However, ASP.NET 5 requires that the Configure method returns void. I could use an async void method, but my understanding is that async void methods are only supposed to be used for event handlers (as per https://msdn.microsoft.com/en-us/magazine/jj991977.aspx among many others).
I was thinking that a better way to do this would be to call the async function without await, call Wait on the returned Task, then cache the results via the Task.Results property, like this:
public void Configure(IApplicationBuilder app, IMemoryCache cache)
{
Task<Data> loadDataTask = DataSource.LoadDataAsync();
loadDataTask.Wait();
cache.Set("somekey", loadDataTask.Result);
// remainder of Configure method omitted for clarity
}
Stephen Walther used a similar approach in a blog post earlier this year. However, it's unclear from that post if this is considered an acceptable practice. Is it?
If this is considered an acceptable practice, what - if any - error handling do I need? My understanding is that Task.Wait() will re-throw any exceptions thrown by the async operation and I haven't provided any mechanism to cancel the async operation. Is simply calling Task.Wait() sufficient?
async void
does have side effects in this case, because it signals to whomever is calling the method that they can proceed with other work while the method is running. SinceConfigure
deals with application setup, continuing to run other parts of the application code before it is finished can have unpredictable consequences. (We ran into this issue, and it made our application go haywire as the dependency injector injected services that weren't yet properly set up). – Daniel Saner