Call async method without await

China☆狼群 提交于 2020-01-15 16:44:12

问题


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.


回答1:


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);
  }
}


来源:https://stackoverflow.com/questions/18079261/call-async-method-without-await

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!