Xamarin表单 - 从错误的线程访问的域

问题描述 投票:0回答:1

也许我错过了一些非常简单的东西,但不管怎么说......

我正在使用Xamarin表单(.NET标准项目),MVVMLight,Realm DB和ZXing条形码扫描程序。

我有一个像这样的真实对象......

public class Participant : RealmObject
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public string Email {get; set;}
    public string RegistrationCode {get; set;}

    //More properties skipped out for brevity
}

我有相应的viewmodel如下:

public class ParticipantViewModel
{
    Realm RealmInstance
    public ParticipantViewModel()
    {
        RealmInstance = Realms.Realm.GetInstance();
        RefreshParticipants();
    }

    private async Task RefreshParticipants() 
    {
        //I have code here that GETS the list of Participants from an API and saves to the device.
        //I am using the above-defined RealmInstance to save to IQueryable<Participant> Participants
    }
}

所有上述工作都很好,我对此没有任何问题。在同一个视图模型中,我还可以启动ZXing扫描仪并扫描表示注册码的条形码。

反过来,这会在扫描后填充下面的属性(也在viewmodel中)...

    private ZXing.Result result;
    public ZXing.Result Result
    {
        get { return result; }
        set { Set(() => Result, ref result, value); }
    }

并调用以下方法(通过ScanResultCommand连接)以获取带有扫描的RegistrationCode的参与者。

    private async Task ScanResults()
    {
        if (Result != null && !String.IsNullOrWhiteSpace(Result.Text))
        {
            string regCode = Result.Text;
            await CloseScanner();
            SelectedParticipant = Participants.FirstOrDefault(p => p.RegistrationCode.Equals(regCode, StringComparison.OrdinalIgnoreCase));
            if (SelectedParticipant != null)
            {
                //Show details for the scanned Participant with regCode
            }
            else
            {
                //Display not found message
            }
        }
    }

我一直得到以下错误....

System.Exception:从错误的线程访问Realm。

由下面的线产生....

SelectedParticipant = Participants.FirstOrDefault(p => p.RegistrationCode.Equals(regCode,StringComparison.OrdinalIgnoreCase));

我不确定这是一个不正确的线程,但任何关于如何从已经填充的IQueryable或Realm表示直接获取扫描参与者的想法将非常感激。

谢谢

xamarin.forms realm mvvm-light .net-standard-2.0 zxing.net
1个回答
0
投票

是的,您在构造函数中获取了一个realm实例,然后从异步任务(或线程)中使用它。您只能从获取引用的线程中访问域。由于您只使用默认实例,因此您应该能够在使用它的函数(或线程)中获取本地引用。尝试使用

    Realm LocalInstance = Realms.Realm.GetInstance();

在函数的顶部并使用它。您需要重新创建Participants查询以使用相同的实例作为其源。无论您何时使用异步任务(线程),都会出现这种情况,因此要么全部更改以在进入时获取默认实例,要么减少访问该领域的线程数。

顺便说一句,我很惊讶你没有从 RefreshParticipants()中获得类似的访问错误 - 也许你实际上并没有从那里通过RealmInstance访问数据。

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