简体   繁体   中英

How to use Control.Dispatcher.BeginInvoke to modify GUI

I need to modify the GUI from inside of a method that takes long time to finish. As I read other posts, one of the solution is to use Control.Dispatcher.BeginInvoke to set the GUI inside the worker thread. However, I don't have a clue how to do this here.

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
    }
}

Try the following:

 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);

   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM