question

fangfangwu avatar image
0 Votes"
fangfangwu asked ·

Setting Textbox.Text from BluetoothLEAdvertisementWatcher's received event throws an exception

I am creating a Bluetooth LE application in C# using a UWP project and have subscribed to get the Received event from the BluetoothLEAdvertisementWatcher.

I can see the data correctly using Debug.Writeline to the Output window, but as soon as I try to assign the same string data to a textbox, I receive a System.Exception message which is an unhandled error.


Here is the code:( I have put "Tester" as my string)

 public sealed partial class MainPage : Page 
 {
     public MainPage()
     {
            this.InitializeComponent();
            BluetoothLEAdvertisementWatcher watcher = new BluetoothLEAdvertisementWatcher();
            watcher.Received += OnAdvertisementReceived;
             …………
      }

     private void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher,    BluetoothLEAdvertisementReceivedEventArgs eventArgs)
     {
            ……. 
            Debug.WriteLine("Tester");
            if (Mytextbox != null)
            {
                 Mytextbox.Text = "Tester";
            }
      }
 }

I have tried using the Dispatcher object to access the textbox but I can't seem to get anything to work. Can someone help me out with a simple solution or point me in the right direction?
Thanks in advance!

windows-uwpwindows-uwp-runtime
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

RoyLi-MSFT avatar image
1 Vote"
RoyLi-MSFT answered ·

Hello,

Welcome to our Microsoft Q&A platform!

Actually, it was a threading issue. The BluetoothLEAdvertisementWatcher's received event is generated on a different thread than the UI thread. As a result, you can't access the TextBox in the normal way as before. In UWP we recommend using Dispatcher.RunAsync to schedule work on the main UI thread.

The following code shows the fix about this issue:

         public void NotifyUser(string strMessage)
         {
             // If called from the UI thread, then update immediately.
             // Otherwise, schedule a task on the UI thread to perform the update.
             if (Dispatcher.HasThreadAccess)
             {
                 UpdateStatus(strMessage);
             }
             else
             {
                 var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateStatus(strMessage));
             }
         }

Thanks.


·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.