问题
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