【问题标题】:Asynchronous Operation in Realm-XamarinRealm-Xamarin 中的异步操作
【发布时间】:2016-12-07 12:24:05
【问题描述】:

我正在 Xamarin 中学习 Realm。

我正在尝试使用Thread 插入一些示例数据。我没有遇到任何问题,直到我在多个线程中调用相同的函数。领域文档说要在 executeTransactionAsync 中执行插入操作,但我在 Realm-Xamarin 中看不到任何类似的方法。

这里是代码。

Thread thread1 = new Thread(() => TestThread.CountTo10("Thread 1"));
thread1.Start();

Thread thread2 = new Thread(() => TestThread.CountTo10("Thread 2"));
thread2.Start();

线程类:

public class TestThread
{
    public static Realm realm;
    public static void CountTo10(string _threadName)
    {
        realm = Realm.GetInstance();
        for (int i = 0; i < 5; i++)
        {
            realm.Write(() =>
            {
                RandomNumber random = new RandomNumber();
                System.Console.WriteLine("Iteration: " + i.ToString() + " Random No: " + random.number.ToString() + " from " + _threadName);
                realm.Manage(random);
            });

            Thread.Sleep(500);
        }
    }
}

领域对象:

public class RandomNumber : RealmObject
{
    public int number { get; set; }

    public RandomNumber()
    {
        number = (new Random()).Next();
    }
}

【问题讨论】:

标签: c# multithreading xamarin realm


【解决方案1】:

问题是你的realm变量是static,这最终会导致非法线程访问。只需删除 static 即可:

public class TestThread
{
    public void CountTo10(string _threadName)
    {
        Realm realm = Realm.GetInstance();
        for (int i = 0; i < 5; i++)
        {
            realm.Write(() =>
            {
                RandomNumber random = new RandomNumber();
                System.Console.WriteLine("Iteration: " + i.ToString() + " Random No: " + random.number.ToString() + " from " + _threadName);
                realm.Manage(random);
            });

            Thread.Sleep(500);
        }
        // no need to call `Realm.close()` in Realm-Xamarin, that closes ALL instances.
        // Realm instance auto-closes after this line
    }
}

【讨论】:

  • 谢谢,它成功了。但是这个代码线程安全吗?我的意思是,我使用相同的领域对象(默认对象)来编写。我刚刚尝试了 5 次异步的 10000 条记录。线程,我没有遇到任何崩溃。但我想确认一下。
  • 我期待一些答案,它使用文件中的 executeTransactionAsync 方法的替代方法。
  • 领域是线程本地的。当您说Realm.getInstance() 时,您使用默认配置为该给定线程打开一个新的 Realm 实例。当您说.Write(() -&gt; {... 时,该调用是跨线程阻塞的,因此在给定时刻只有一个线程可以write。而且因为所有托管的 RealmObject(和 Realm 实例)都是线程受限的,因此,根据定义它们也是线程安全的:它们不能从其他线程读取或修改。
  • 知道了,谢谢。
猜你喜欢
  • 2023-03-16
  • 2020-10-25
  • 1970-01-01
  • 1970-01-01
  • 2016-10-31
  • 2016-02-23
  • 2016-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多