0

I have the following code, that I call when a page is loaded:

public StartPage()
{
    NavigationPage.SetHasNavigationBar(this, false);
    InitializeComponent();
    Task.Run(() =>
    {
        Scan_Function();
    });
}

In Scan_Function(), I have a stopwatch and a bunch of if-statements, that are supposed to make the text of bleText label change dynamically:

public void Scan_Function()
{
    Stopwatch sw = new Stopwatch();
    sw.Start();
    while (sw.Elapsed.TotalMilliseconds <= 10000)
    {   
        if (sw.Elapsed.TotalMilliseconds >= 1000 && sw.Elapsed.TotalMilliseconds <= 1050)
        {
                bleText.Text = "Scanning.";
        }
        else if (sw.Elapsed.TotalMilliseconds >= 2000 && sw.Elapsed.TotalMilliseconds <= 2050)
        {
                bleText.Text = "Scanning..";
        }
      ....... continues 
    }
        sw.Stop();
        bleText.Text = "Couldn't connect";
        bleText.TextColor = Color.Red;
}

I'm calling my Scan_Function() from Task.Run(), because I want the method to run asynchronously with everything else so that the user can still press buttons etc.

My problem is though, that nothing happens! I'm suspecting that something is wrong with bleText.Text, cause my debugger reaches it and seems to get stuck without updating anything or jumping out of the loop. If i comment my if-statements, it runs through the loop, but get stuck once it reaches bleText.Text outside the loop.

What am I doing wrong here?

Jeppe Christensen
  • 1,680
  • 2
  • 21
  • 50
  • Possible duplicate of [C# in Async Task change Label Text](https://stackoverflow.com/questions/30281387/c-sharp-in-async-task-change-label-text) – mjwills Sep 25 '18 at 13:13
  • Why don't you use a timer? `Stopwatch` isn't a timer or even an "active" class. It stores the processor tick value when `Start` is called and uses it to calculate a duration when `Elapsed` is called. In any case you just *can't* update the UI from another thread, no matter the OS. – Panagiotis Kanavos Sep 25 '18 at 13:22

1 Answers1

3

You can't update the UI from a background thread. Use BeginInvokeOnMainThread() to force your code to execute on the UI thread

Device.BeginInvokeOnMainThread( () => {
    bleText.Text = "Couldn't connect";
    bleText.TextColor = Color.Red;
} );
Jason
  • 86,222
  • 15
  • 131
  • 146