如何对等待第一次调用结果的异步方法进行不同的调用? [英] How to make different calls to an async method waiting for the result of first call?

查看:51
本文介绍了如何对等待第一次调用结果的异步方法进行不同的调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一种方法可以从服务器获取数据

Let's say I have a method it gets data from server

Task<Result> GetDataFromServerAsync(...)

如果正在进行通话,我不想向服务器发起新请求,而是等待原始请求完成.

If there is an ongoing call in progress, I don't want to start a new request to server but wait for the original to finish.

假设我有

var result = await objet.GetDataFromServerAsync(...);

在另一个地方,几乎在同一时间打了我第二个电话

and in a different place, called almost at the same time I have a second call

var result2 = await objet.GetDataFromServerAsync(...);

如果第一个未完成,我不希望第二个启动对服务器的新请求.我希望两个通话在第一个通话结束时都能得到相同的结果.这是一个概念证明,我可以选择,但是我想看看这样做有多么容易.

I don't want the second to start a new request to server if the first didn't finish. I want both calls to get the same result as soon as first call finish. This is a proof of concept, I have options but I wanted to see how easy it's to do this.

推荐答案

下面是使用 Lazy< Task< T>> :

var lazyGetDataFromServer = new Lazy<Task<Result>>
    (() => objet.GetDataFromServerAsync(...));

var result  = await lazyGetDataFromServer.Value;
var result2 = await lazyGetDataFromServer.Value;

这两个 await 是否从单独的线程完成并不重要,因为 Lazy< T> 是线程安全的,所以 result2 如果第二秒仍将等待并使用 result 的相同输出.

It doesn't matter if these 2 awaits are done from separate threads as Lazy<T> is thread-safe, so result2 if ran second will still wait and use the same output from result.

使用此处的代码,您可以包装将其添加到名为 AsyncLazy< T> 的类中,并添加自定义的 GetAwaiter ,这样您就可以 await ,而无需执行 .Value ,非常整洁=)

Using the code from here you can wrap this up in a class called AsyncLazy<T>, and add a custom GetAwaiter so that you can just await it without the need to do .Value, very tidy =)

这篇关于如何对等待第一次调用结果的异步方法进行不同的调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆