2

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!

  • Your second code example looks valid from what has been provided. Could you provide more details about what is happening in the assignment of the Time and Value properties? If you are reading from existing RealmObject instances to calculate these values then you could see such a threading error. – C8H10N4O2 May 15 '19 at 05:23

0 Answers0