GUI not updating c# winforms in the same thread

2019-08-03 17:04发布

private void buttonSave_Click(object sender, EventArgs e)
{
    textBox1.Text = "DATA is being copied.";

    //my own function to cpy files, working properly
    copyDirectory(sourceFolderPath, destFolderPath);
}

Copying takes 3 seconds, but i cannot see TextBox with text="DATA is being copied. before it goes into the copyDirectory function", it only updates the text box after finishing copy, what is the Problem? i am not using another thread in copying.

标签: c# winforms
1条回答
对你真心纯属浪费
2楼-- · 2019-08-03 17:13

This is because of how Windows Forms handles events. Windows Forms is executing all events synchronously. Which means that when a button is clicked, all code in all attached events are executed, before anything else happens.

This means that until the copying finishes (that is, the method returns), the textbox will not be visibly updated.

There are several fixes for this. One fix is to have the button click start a timer, that executes 100 milliseconds later. And then when the timer executes, perform the copying.

Another (my preferred) would be to execute the copyDirectory method inside a Task:

Task.Factory.StartNew(() => copyDirectory(sourceFolderPath, destFolderPath))

Note: This means that the code runs on a different thread, so if you want to update the textbox to say something like "Completed!" when it's finished, you'll need to do this

Invoke(new Action(() => textbox.Text = "Completed!");
查看更多
登录 后发表回答