我需要从一个需要很长时间才能完成的方法内部修改 GUI。当我阅读其他帖子时, 解决方案之一是使用 Control.Dispatcher.BeginInvoke 在工作线程内设置 GUI。 但是,我不知道如何在这里执行此操作。
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Task.Factory.StartNew( () =>
{
ProcessFilesThree();
});
}
private void ProcessFilesThree()
{
string[] files = Directory.GetFiles(@"C:\temp\In", "*.jpg", SearchOption.AllDirectories);
Parallel.ForEach(files, (currentFile) =>
{
string filename = Path.GetFileName(currentFile);
// the following assignment is illegal
this.Text = string.Format("Processing {0} on thread {1}", filename,
Thread.CurrentThread.ManagedThreadId);
});
this.Text = "All done!"; // <- this assignment is illegal
}
}
最佳答案
尝试以下操作:
msg = string.Format("Processing {0} on thread {1}", filename,
Thread.CurrentThread.ManagedThreadId);
this.BeginInvoke( (Action) delegate ()
{
this.Text = msg;
});
关于c# - 如何使用 Control.Dispatcher.BeginInvoke 修改 GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6170427/