简体   繁体   中英

c# - How to execute code line by line?

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.

Application.DoEvents()

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

Label1.Update()
Application.DoEvents()

You usually need both.

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

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

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM