所以我有一个使用 MVVM 模式的 WPF 应用程序 (Caliburn.Micro)。我连接了 View 和 View 模型,基本上缺少的是数据。数据将从 WCF 服务、本地存储或内存/缓存中“按需”检索 - 原因是允许离线模式并避免不必要的服务器通信。另一个要求是异步检索数据,这样 UI 线程就不会被阻塞。
所以我想创建某种 View 模型用来请求数据的“AssetManager”:
_someAssetManager.GetSomeSpecificAsset(assetId, OnGetSomeSpecificAssetCompleted)
注意是异步调用。不过,我遇到了一些不同的问题。如果不同的 View 模型在(大致)同一时间请求相同的 Assets ,我们如何确保我们不做不必要的工作并且它们都获得我们可以绑定(bind)的相同对象?
不确定我的方法是否正确。我一直在浏览 Reactive Framework——但我不知道如何在这种情况下使用它。关于我可以使用的框架/技术/模式的任何建议?这似乎是一个相当普遍的场景。
最佳答案
Dictionary<int, IObservable<IAsset>> inflightRequests;
public IObservable<IAsset> GetSomeAsset(int id)
{
// People who ask for an inflight request just get the
// existing one
lock(inflightRequests) {
if inflightRequests.ContainsKey(id) {
return inflightRequests[id];
}
}
// Create a new IObservable and put in the dictionary
lock(inflightRequests) { inflightRequests[id] = ret; }
// Actually do the request and "play it" onto the Subject.
var ret = new AsyncSubject<IAsset>();
GetSomeAssetForReals(id, result => {
ret.OnNext(id);
ret.OnCompleted();
// We're not inflight anymore, remove the item
lock(inflightRequests) { inflightRequests.Remove(id); }
})
return ret;
}
关于c# - MVVM 和异步数据访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10075246/