无需等待就调用异步方法

编程入门 行业动态 更新时间:2024-10-26 23:28:29
本文介绍了无需等待就调用异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我致力于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); } }

更多推荐

无需等待就调用异步方法

本文发布于:2023-11-23 10:20:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621093.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!