2016-12-07 41 views
2

我在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(); 
    } 
} 
+0

的xamarin文檔:https://realm.io/docs/xamarin/latest/ – EpicPandaForce

回答

2

的問題是,你的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 
    } 
} 
+0

謝謝,它的工作。但是這個代碼線程安全嗎?我的意思是,我使用相同的領域對象(默認的)來編寫。我剛剛嘗試了5個異步中的10000條記錄。線程,我沒有得到任何崩潰。但我想確認一下。 –

+0

我在等待文檔中使用executeTransactionAsync方法的替代方法。 –

+0

領域是線程局部的。當你說'Realm.getInstance()'時,你使用默認配置爲給定的線程打開一個新的Realm實例。當你說'.Write(() - > {...'時,這個調用在線程間阻塞,所以只有一個線程能夠在給定的時刻*寫*。並且因爲所有被管理的RealmObjects(和Realm實例)都是線程受限,因此,*它們在定義上也是線程安全的*:它們不能被其他線程讀取或修改。 – EpicPandaForce