【问题标题】:C# async calls and realm instancesC# 异步调用和领域实例
【发布时间】:2019-03-07 23:22:19
【问题描述】:

我正在将 Realm 与 Xamarin Forms 项目一起使用,并且我已经阅读了有关如何跨线程共享领域实体实例的信息。

给定下面的代码,是使用第100行得到的route,然后在第104行调用awaited后在第109行再次访问,危险吗?

我是使用 Realm 的新手,但如果这是真的,那么必须在任何/每个 awaited 调用之后获取 Realm 的新实例和正在使用的任何对象。看起来很繁琐……

【问题讨论】:

    标签: xamarin xamarin.forms realm realm-mobile-platform


    【解决方案1】:

    正在使用100行获取的路由,在104等待调用后又在109行再次访问,危险吗?

    是的,在下一次 foreach 迭代中,您将得到一个不同的托管线程,Realm 将抛出一个不同的线程访问异常。

    关键是使用SynchronizationContext,这样您的等待延续就在同一个线程上(当然,由于您将在不同的线程中,请跳过使用基于 Realm 的异步方法)

    使用 Stephen Cleary 的 Nito.AsyncEx(他是同步上下文之王?)

    回复:how can i force await to continue on the same thread?

    var yourRealmInstanceThread = new AsyncContextThread();
    await yourRealmInstanceThread.Factory.Run(async () =>
    {
        var asyncExBasedRealm = Realm.GetInstance();
        var routes = asyncExBasedRealm.All<UserModel>();
        foreach (var route in routes)
        {
            // map it
            // post it
            await Task.Delay(TimeSpan.FromMilliseconds(1)); // Simulate some Task, i.e. a httpclient request.... 
            // The following continuations will be executed on the proper thread
            asyncExBasedRealm.Write(() => route.Uploaded = true);
        }
    });
    

    使用 SushiHangover.RealmThread

    不久前,我为 Realm 编写了一个简单 SynchronizationContext,它可以满足我的需求,并且有一个专门用于 Realm 的 API。

    using (var realmThread = new RealmThread(realm.Config))
    {
        await realmThread.InvokeAsync(async myRealm =>
        {
            var routes = myRealm.All<UserModel>();
            foreach (var route in routes)
            {
                // map it
                // post it
                await Task.Delay(TimeSpan.FromMilliseconds(1)); 
                // The following continuations will be executed on the proper thread
                myRealm.Write(() => route.Uploaded = true);
            }
        });
    }
    

    注意:对于不太了解SynchronizationContext 的人,我强烈建议使用Nito.AsyncEx 作为通用解决方案,该解决方案得到很好的支持,并且来自Stephen Cleary。 .. 我在绝大多数项目中都使用它。

    【讨论】:

    • 您好@SushiHangover,我目前在我的 xamarin 项目中遇到了著名的“从错误线程访问的领域”的严重问题。要使用 Nito.AsyncEx,是否需要进行任何其他配置或仅作为答案中的示例?您有可以与我分享的链接或示例吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多