1

I working on image loader library for Windows Phone 8+ applications, and of course it supports caching on disk.

So, I need to save image on disk asynchronously without awaiting result:

// Async saving to the storage cache without await
// ReSharper disable once CSharpWarnings::CS4014
Config.StorageCacheImpl.SaveAsync(imageUrl, downloadResult.ResultStream)
    .ContinueWith(
        task => 
        {
            if (task.IsFaulted || !task.Result)
            {
                Log("[error] failed to save in storage: " + imageUri);
            }
        }
);

As you can see, SaveAsync() is async method and it returns Task<bool>, where bool result is true if image was saved.

The problem is that compiler shows warning because I am not awaiting the result of the async method, but, I do not need to await it, i need to return downloaded image to the user code as fast as it possible, after invoke of SaveAsync() I return downloaded image.

So I am caching image to the IsolatedStorageFile asynchronously and moreover — it does not matter, will it be cached or not, because if not — JetImageLoader will load it again.

Is it possible to disable this warning?

P.S. if you want to see JetImageLoader sources, I can give you a link to GitHub.

Artem Zinnatullin
  • 4,305
  • 1
  • 29
  • 43

1 Answers1

8

The compiler warning is there because it's almost always a mistake to do this. For one thing, you don't get any kind of notification that the task completed, and you also don't get notified of errors.

To avoid the compiler warning, you can just assign it to an unused local variable, like this:

var _ = Config.StorageCacheImpl.SaveAsync...

In your case, I'd also recommend using a helper method instead of ContinueWith to make the code a little cleaner:

private static async Task SaveAsync(string imageUrl, Stream resultStream)
{
  bool success = false;
  try
  {
    success = await Config.StorageCacheImpl.SaveAsync(imageUrl, downloadResult.ResultStream);
  }
  finally
  {
    if (!success)
      Log("[error] failed to save in storage: " + imageUri);
  }
}
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • Thank you for suggestion with local variable, it helped :) About `ContinueWith` — I put it there because library user can use his own implementations of cache component, so he may forget to add this in his impl ;) – Artem Zinnatullin Aug 07 '13 at 06:22
  • Oh, I got it, you suggested to create a method for that instead of using `ContinueWith`, ok – Artem Zinnatullin Aug 07 '13 at 06:24