Backgroup
Backgroup

Reputation: 29

ProgressBar control parallel with Method

I'm trying to run a ProgressBar when the method starts, and stop the bar when the method ends.

The time of the ProgressBar has to run in parallel with the time of the method. When I call the method the ProgressBar start; when the method ends theProgressBar` stops.

I have tried:

progressBar1.Minimum = 0;
progressBar1.Maximum = 200;
int i = 0;
var myVar = var.empty;
While(myVar.Lenght =! 0)
{
   myVar = myMethod();
   i++;
   progressBar1.Value = i;
}

Any suggestion to make it work?

Upvotes: 1

Views: 94

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70652

Without a good Minimal, Reproducible Example that reliably reproduces the problem, it's impossible to know for sure what the issue is. However, it's possible to make an educated guess.

In Xamarin, like in all the other mainstream GUI APIs, you have one thread that owns all of the UI. Only this thread refreshes the screen, and as long as that thread is kept busy doing other things, it can't do that. Changes to properties of visual elements aren't shown to the user.

It is probable that the code you posted is being executed on that main UI thread. Until you return from whatever method contains the code, the UI cannot be updated. Your own code is occupying the thread's attention, and the UI cannot be updated.

Without a code code example, there's no way to provide specific advice about how to fix it. However, the general approach involves moving the time-consuming code to a background thread, and then using some mechanism to update the progress bar periodically from there.

Note that like other mainstream GUI APIs, there is also a requirement that your code interacts with UI-related objects only on that main UI thread. There are typically special methods provided by such APIs, and Xamarin is no exception. One of the methods you can use is InvokeOnMainThread(). You can look that up for more details about how to use it.

In the meantime, here is another Stack Overflow Q&A that illustrates the basic concepts of the use of a ProgressBar:
How to create a progress bar with rounded corners in iOS using Xamarin.Forms

That example both shows one way to use a background thread to do the long-running work (in that case, simulated with a call to Task.Delay()), as well as how to use InvokeOnMainThread() to update the ProgressBar itself.

Upvotes: 1

Related Questions