-1

why this code wont work without Dispatcher.RunAsync and what does it do? without Dispatcher its throwing error at copying value to textv.Text " thats its on different thread"

     async void Current_GeofenceStateChanged(GeofenceMonitor sender, object args)
    {
        var reports = sender.ReadReports();

        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            foreach (var report in reports)
            {
                GeofenceState st = report.NewState;
                Geofence gf2 = report.Geofence;
                if (st == GeofenceState.Entered)
                {
                    textv2.Text = "Hello"; //XAML TEXT
                }
                else if(st==GeofenceState.Exited)
                {
                    textv2.Text = "Bye";
                }
            }
        });

    }
pavinan
  • 1,275
  • 1
  • 12
  • 23

1 Answers1

1

The Event Current_GeofenceStateChanged is being fired outside of the GUI thread and only the GUI thread can change GUI elements. Dispatcher.RunAsync says the code inside should run on the GUI thread so it works.

if you put the result on a string variable it will work if you only put:

  Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => textv2.Text = StringVariable;);

EDIT: I only noticed that you have XAML code later you can just put the string on a property and bind the property to the text value of the text box letting you free from the Dispatcher.

<TextBox Text="{Binding StringVariable}"/>

and on the code just have

public string StringVariable { get; set; }

than on the method just set the value to the property

StringVariable = "bla bla";
Pedro.The.Kid
  • 1,968
  • 1
  • 14
  • 18