Reputation: 3896
In my c# winform app I have a button which when clicked, it performs some calculations which can tke some time.
I also have a label.visible = false
which I would like to label.visible = true
right after the button click so that the user can see the app working away.
The thing is even when label.visible = true
is the first thing in the button1_Click(object sender, EventArgs e)
method, it only toggles to visible at the very end, after the calculation is performed.
How can I show the label right after the button_click?
Upvotes: 2
Views: 456
Reputation: 1764
Like others have said: You are performing your work on the UI Thread. I am showing you another valid way of achieving what you need. You can move your work to a separate thread using an anonymous delegate.
(new System.Threading.Thread(() =>
{
dowork(); // What ever work you need put here.
})).Start();
Upvotes: 1
Reputation: 19656
If you need your application to remain responsive whilst your app is processing, take a look at Background Worker
You can force your form to update & process any background messages by calling:
Application.DoEvents();
Just after you have changed your label - although this is probably a bit of a hacky solution.
Upvotes: 4
Reputation: 33149
There are several ways to tackle this.
One way (the simplest) is to call
this.Refresh();
right after you set the Label to visible.
Another is to do your calculations in a background thread. The easiest way to do that is to use a BackgroundWorker
. Then your main thread can just continue serving the UI (refreshing the form, responding to buttons etc.) while the background worker thread performs the computation.
See http://www.dotnetperls.com/backgroundworker for more on background worker threads.
Upvotes: 1
Reputation: 14682
Your calculation is being performed on the UI thread. This means that it is blocking the UI from refresshing after you have set the visibility of the label. You should consider doing the calculation on another thread using a Task. This will allow the UI to be responsive during what it seems is a long operation that can run in the background.
e.g.
var taskCalc = Task.Factory.StartNew(() => //Do Calculation );
Upvotes: 2