q0987
q0987

Reputation: 35982

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

Upvotes: 1

Views: 5524

Answers (2)

dugas
dugas

Reputation: 12463

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

   }
}

Upvotes: 1

Richard Schneider
Richard Schneider

Reputation: 35477

Try the following:

 msg = string.Format("Processing {0} on thread {1}", filename,
            Thread.CurrentThread.ManagedThreadId);
 this.BeginInvoke( (Action) delegate ()
    {
        this.Text = msg;
    });

Upvotes: 3

Related Questions