如何使用Control.Dispatcher.BeginInvoke修改GUI

本文关键字:修改 GUI BeginInvoke Dispatcher 何使用 Control | 更新日期: 2023-09-27 17:58:07

我需要从一个需要很长时间才能完成的方法内部修改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
    }
}

如何使用Control.Dispatcher.BeginInvoke修改GUI

尝试以下操作:

 msg = string.Format("Processing {0} on thread {1}", filename,
            Thread.CurrentThread.ManagedThreadId);
 this.BeginInvoke( (Action) delegate ()
    {
        this.Text = msg;
    });
private void ProcessFilesThree()
{
   // Assuming you have a textbox control named testTestBox
   // and you wanted to update it on each loop iteration
   // with someMessage
   string someMessage = String.Empty;
   for (int i = 0; i < 10; i++)
   {
      Thread.Sleep(1000); //Simulate a second of work.
      someMessage = String.Format("On loop iteration {0}", i);
      testTextBox.Dispatcher.BeginInvoke(new Action<string>((message) =>
      {
          testTextBox.Text = message;
      }), someMessage);
   }
}