c# - MVVM 和异步数据访问

标签 c# wpf mvvm system.reactive caliburn.micro

所以我有一个使用 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/

相关文章:

c# - 如何通过 C# 控制台循环访问 Excel 应用程序中的列?

javascript - 来自 Web API 的空白请求、状态和错误

C# - MVVM 中的第二个选项卡项中不显示弹出窗口

c# - 如何在列表框中设置文本 block 的背景颜色?

c# - Caliburn.Micro View 切换

c# - 如何找出 .net 类实现了哪些接口(interface)?

.net - WPF:为什么这会导致堆栈溢出异常?

wpf - 单元测试 : hard dependency MessageBox. Show()

android - 使用Android MVVM,如何避免在回收站适配器中再次设置相同的数据?

c# - PInvoke 在类定义中不起作用