tags:

views:

120

answers:

6

Take this example code

private void test()
{
    Label1.Text = "Function 1 started.";
    function1(); //This function takes a while to execute say 15 seconds.
    Label2.Text = "Function 1 finished.";
}

If this is run you would never see Function 1 started. So my question is, Are there any c# functions that could be call the show the label change. Something like so

private void test()
{
    Label1.Text = "Function 1 started.";
    this.DoProcess();       //Or something like this.
    function1();             
    Label2.Text = "Function 1 finished.";
}

I know this could be done using threads but a was wondering whether there was another way.

Thank you in adv.

+3  A: 

if this is a WinForms app, Label1.Update(). If that's not enough:

Label1.Update()
Application.DoEvents()

You usually need both.

egrunin
+5  A: 

Application.DoEvents()

Yuriy Faktorovich
+3  A: 

Your function1 should probably run asynchronously, to not freeze the UI. Take a look at the BackgroundWorker class.

Jordão
+1  A: 

Since the UI thread is busy running your code, it won't stop to refresh the form after you change the label's value, wating until it's done with your code before it repaints the form itself. You could do it with threads or, as others have already stated, you could use Application.DoEvents, which will force the UI thread to pause execution and repaint the forms.

rwmnau
+3  A: 
var context = TaskScheduler.FromCurrentSynchronizationContext(); // for UI thread marshalling
Label1.Text = "Function 1 started.";
Task.Factory.StartNew(() =>
{
     function1();           
}).ContinueWith(_=>Label2.Text = "Function 1 finished.", context);

.NET 4 Task Parallel Library

Hasan Khan
Does `.ContinueWith()` execute in the GUI thread? I don’t think so, in which case you can’t change Label2.Text from another thread. You can use `.ContinueWith(_ => Label2.Invoke(() => Label2.Text = ...))` though.
Timwi
Corrected it already, thanks for pointing it out. with correct synchronization context passed there won't be any problems.
Hasan Khan
A: 

Where is private void test() called?

If not in the UI thread, then you may need a delegate:

public delegate void UpdateLabelStatus(string status);

...

private void test()
{

     Invoke(new UpdateLabelStatus(LabelStatus1), status);
     ...

}

private void LabelStatus1(string status)
{

     Label1.Text = status;
}

Otherwise, you should be able to do Label1.Update(); and then Application.DoEvents();

0A0D