我有一个调用 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/