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

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

在同步环境中,我可以将yield return与Tasks配合使用,并且无法实现异步/等待收益。

我怎么解决这个问题?

最佳答案

您可以使用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/

10-15 15:48
查看更多