为什么当整个操作在同一个线程上执行时,Realm会抛出从错误线程访问的Realm?

问题描述 投票:0回答:1
Task.Factory.StartNew(async () =>
            {
                try
                {
                    ShowCaseInfo existingShowcase = DBService.GetDB().FetchShowcaseInfo();
                    string previousResponse = existingShowcase?.SerializedResponse;
                    Response response = await CloudService.GetCloudService().FetchShowcase();

                    if (response.Status == ResponseStatus.SUCCESS && !string.Equals(previousResponse, response.Data))
                    {
                        ShowCaseInfo showcaseInfo = JsonConvert.DeserializeObject<ShowCaseInfo>(response.Data, _settings);
                        showcaseInfo.SerializedResponse = response.Data;
                        DBService.GetDB().InsertOrUpdateShowcase(showcaseInfo);
                        FetchShowcaseProducts(showcaseInfo.Showcases);
                    }
                    else
                    {
                        List<Showcase> emptyCases = new List<Showcase>();
                            if (existingShowcase != null)
                            {
                                foreach (Showcase showcase in existingShowcase.Showcases)
                                {
                                    if (showcase.Products.Count == 0)
                                    {
                                        emptyCases.Add(showcase);
                                    }
                                }
                            }
                        FetchShowcaseProducts(emptyCases);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            });

foreach (Showcase showcase in existingShowcase.Showcases)这一行是在抛出异常。同样的,在if条件下!string.Equals(previousResponse, response.Data),如果我把previousResponse作为existingShowcase.SerializedResponse来访问,而不是本地变量,就会抛出异常。根据文档,我们不应该跨线程传递对象,但在这种情况下,所有的操作都在同一个线程中。

c# .net xamarin.forms realm realm-mobile-platform
1个回答
1
投票

在这种情况下,所有的操作都在同一个线程中。

不,实际上不是。这是因为 await 作品。

await 异步行动,它捕捉到了它当前的上下文 - 要么 SynchronizationContext.CurrentTaskScheduler.Current. 在这种情况下,上下文是线程池上下文。所以,当方法在执行完 await,它可以恢复执行 任何 线程池线。

© www.soinside.com 2019 - 2024. All rights reserved.