我在Xamarin中學習Realm。Realm中的異步操作-Xamarin
我想通過使用Thread
插入一些示例數據。我不會遇到任何問題,直到我在多個線程中調用相同的函數。領域文檔說要在executeTransactionAsync
內執行插入操作,但我沒有在Realm-Xamarin中看到任何類似的方法。
這是代碼。
Thread thread1 = new Thread(() => TestThread.CountTo10("Thread 1"));
thread1.Start();
Thread thread2 = new Thread(() => TestThread.CountTo10("Thread 2"));
thread2.Start();
Thread類:
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();
}
}
的xamarin文檔:https://realm.io/docs/xamarin/latest/ – EpicPandaForce