我致力于Windows Phone 8+应用程序的图像加载器库,当然它支持磁盘上的缓存.
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); } } );如您所见,SaveAsync()是异步方法,它返回Task<bool>,如果保存图像,则bool结果为true.
As you can see, SaveAsync() is async method and it returns Task<bool>, where bool result is true if image was saved.
问题是编译器显示警告,因为我没有在等待异步方法的结果,但是,我不需要等待,我需要返回调用SaveAsync()后,将下载的图像尽快地下载到用户代码中.
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.
所以我正在异步将图像缓存到IsolatedStorageFile ,而且-没关系,是否缓存,因为如果没有,JetImageLoader会再次加载它.
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.
是否可以禁用此警告?
P.S.如果您想查看JetImageLoader的资源,我可以给您一个指向GitHub的链接.
P.S. if you want to see JetImageLoader sources, I can give you a link to GitHub.
推荐答案出现编译器警告是因为这样做几乎总是一个错误.一方面,您不会收到有关任务已完成的任何通知,也不会收到有关错误的通知.
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...对于您而言,我还建议您使用辅助方法而不是ContinueWith来使代码更简洁:
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); } }更多推荐
无需等待就调用异步方法
发布评论