开发者

c# - How to execute code line by line?

开发者 https://www.devze.com 2023-01-11 01:50 出处:网络
Take this example code private void test() { Label1.Text = \"Function 1 started.\"; function1(); //This function takes a while to execute say 15 seconds.

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# funct开发者_StackOverflow中文版ions 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();

0

精彩评论

暂无评论...
验证码 换一张
取 消