c# - 从异步方法返回部分结果

标签 c# asynchronous async-await task

我有一个调用 Web 服务以异步检索数据的类。为了提高性能,我实现了一个客户端缓存,用于检查请求的数据是否在本地可用。该类返回存储在缓存中的所有数据,并调用网络服务来获取剩余数据。

我可以将缓存的数据返回给调用者然后继续进行网络调用,还是必须进行调用并返回完整的数据集?

在同步环境中,我可以使用 yield return,通过 Tasks 和 async/await yield 是不可能的。

我该如何解决这个问题?

最佳答案

您可以使用 Observable

 // in your UI
            var result = new ObservableCollection<Data>(); // this is your list to bind to UI

            IsBusy = true; // indicate that work is done
            yourDataSource.GetData(2000).Subscribe(batch =>
            {
                foreach (var d in batch)
                {
                    result.Add(d);
                }
            },
                exception =>
                {
                    Log.Error(exception);
                    IsBusy = false;
                },
                () =>
                {
                    // this means done
                    IsBusy = false;
                }
            )

            // or you can await the whole thing
            try
            {
                IsBusy = true;
                await yourDataSource.GetData(5).Do(batch =>
                {
                    foreach (var d in batch)
                    {
                        result.Add(d);
                    }
                });
            }
            finally
            {
                IsBusy = false;
            }

您的数据来源:

  IObservable<IList<Data>> GetData(int args)
        {
            var result = new Subject<IList<Data>>();

            Task.Run(async () =>
            {
                try
                {
                    var formCache = await GetFromCache(args);

                    result.OnNext(fromCache);

                    while (moreBatches)
                    {
                        result.OnNext(GetNextBatch(args));
                    }

                    result.OnCompleted();
                }
                catch (Exception e)
                {
                    result.OnError(e);
                }
            });

            return result;
        }

如果您使用的是 WPF、Xamarin.Forms 或 UWP,我强烈推荐 ReactiveCommand它可以返回 observable 并为您完成整个 IsBusy 的事情。

关于c# - 从异步方法返回部分结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49747874/

相关文章:

java - 异步 Servlet 不在单独的线程中执行异步任务

c# - 使用 jQuery 的 $.ajax() 调用 C# async WebMethod 无限挂起

javascript - async/await 返回 Promise { <pending> }

c# - 如何修复 HTTP 错误 500.22 - 内部服务器错误检测到不适用于集成托管管道模式的 ASP.NET 设置

c# - 我必须停止 System.Timers.Timer 吗?

ios - 如何同步使用 AFNetworking 2.0 库?

Android:在使用 Retrofit 继续执行之前等待 API 的响应

c# - XML 和 & 字符

c# - 无法识别 mysql 请求中的问题

typescript - 如何将 onload promise 转换为 Async/Await