Search code examples
c#multithreadingxamarinrealm

Asynchronous Operation in Realm-Xamarin


I am learning Realm in Xamarin.

I am trying to insert some sample data by using Thread. I don't face any issue, until I call the same function in multiple threads. The realm document says to perform insert operations inside executeTransactionAsync , but I don't see any methods like that in Realm-Xamarin.

Here is the code.

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

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

Thread class:

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);
        }
    }
}

Realm Object:

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

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

Solution

  • The problem is that your realm variable is static, and this will eventually result in illegal thread access. Just remove static and you'll be good to go:

    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
        }
    }