how to fix the threading issues in blocks

60 Views Asked by At

when I am trying to change values of variable in

 GalaSoft.MvvmLight.Messaging.Messenger.Default.Register<status>(this, async Status=>
            {
              this.txt1.text = "Hi"
            });

enter image description here

I am really confused on how to deal with this error

1

There are 1 best solutions below

2
On

You can only update the UI from the main UI thread. In order to do so you need to use the Device.BeginInvokeOnMainThread method to invoke the update to the UI on the UI thread. Like so:

GalaSoft.MvvmLight.Messaging.Messenger.Default.Register<status>(this, async Status=>
        {
             Device.BeginInvokeOnMainThread(() =>
             {
                this.txt1.text = "Hi";
             });
        });

Each platform has it's own native method to invoke on the UI Thread. In WinPhone:

GalaSoft.MvvmLight.Messaging.Messenger.Default.Register<status>(this, async Status=>
        {
             var coreWindow = CoreWindow.GetForCurrentThread();

             // Dispatcher needed to run on UI Thread
             dispatcher = coreWindow.Dispatcher;

             // RunAsync all of the UI info.
             dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
             {
                 this.txt1.text = "Hi";
             });
        });