GUI 不在同一线程中更新 c# winforms
GUI not updating c# winforms in the same thread
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);
}
复制需要 3 秒,但我看不到带有 text="DATA is being copied. before it goes into the copyDirectory function" 的文本框,它仅在完成复制后更新文本框,这是什么问题?我没有在复制中使用另一个线程。
这是因为 Windows 表单处理事件的方式。 Windows Forms 正在同步执行所有事件。这意味着当单击按钮时,所有附加事件中的所有代码都会在其他任何事情发生之前执行。
这意味着在复制完成之前(即方法returns),文本框不会明显更新。
对此有几个修复。一种解决方法是单击按钮启动一个计时器,该计时器在 100 毫秒后执行。然后当定时器执行时,执行复制。
另一个(我的首选)是在任务中执行 copyDirectory 方法:
Task.Factory.StartNew(() => copyDirectory(sourceFolderPath, destFolderPath))
注意:这意味着代码在不同的线程上运行,因此如果您想在完成时更新文本框以显示类似 "Completed!" 的内容,您需要执行此操作
Invoke(new Action(() => textbox.Text = "Completed!");
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);
}
复制需要 3 秒,但我看不到带有 text="DATA is being copied. before it goes into the copyDirectory function" 的文本框,它仅在完成复制后更新文本框,这是什么问题?我没有在复制中使用另一个线程。
这是因为 Windows 表单处理事件的方式。 Windows Forms 正在同步执行所有事件。这意味着当单击按钮时,所有附加事件中的所有代码都会在其他任何事情发生之前执行。
这意味着在复制完成之前(即方法returns),文本框不会明显更新。
对此有几个修复。一种解决方法是单击按钮启动一个计时器,该计时器在 100 毫秒后执行。然后当定时器执行时,执行复制。
另一个(我的首选)是在任务中执行 copyDirectory 方法:
Task.Factory.StartNew(() => copyDirectory(sourceFolderPath, destFolderPath))
注意:这意味着代码在不同的线程上运行,因此如果您想在完成时更新文本框以显示类似 "Completed!" 的内容,您需要执行此操作
Invoke(new Action(() => textbox.Text = "Completed!");