Write to Realm from another thread (event)

45 Views Asked by At

I'm writing a .NET UWP app for real-time monitoring of a Bluetooth LE device. I am succesful in using Realm DB within MainPage, Content Dialogs, etc. For receiving data of the BLE device, I have defined an event Characteristic_ValueChanged. My goal is to write to Realm DB during this event.

My code:

public sealed partial class MainPage : Page
    {
        public IQueryable<General> Generals { get; private set; }
        public IQueryable<Person> Users { get; private set; }

        private Realm realm = Realm.GetInstance();

        public MainPage()
        {
            this.InitializeComponent();

            Generals = realm.All<General>();
            Users = realm.All<Person>();
        }

// some other code, defined a GattCharacteristic.ValueChanged += Characteristic_ValueChanged;

        void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            realm.Write(() =>
            {
                Users.ElementAt(id).Measurements.Add(new Measurement
                {
                    Time = ...;
                    Value = ...;
                });
            });
        }
    }

Unfortunately, the Realm crashes with "wrong thread error"/"interface assigned to another thread".

I've tried to create a new Realm Instance inside the event

        void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            var realm2 = Realm.GetInstance();
            var measurement = realm2.All<Person>().ElementAt(id).Measurements;
            realm2.Write(() =>
            {
                measurement.Add(new Measurement
                {
                    Time = ...;
                    Value = ...;
                });
            });
        }

and call

realm.Dispose()

in the main thread (Main Page) before any event occurs, but I'm still out of luck. I read in the documentation something about ThreadSafeReference, but I'm not sure, how to properly use it in my case or if it's any helpful for me.

How can I write to Realm database within the event? Thank you!

0

There are 0 best solutions below