Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread-safe updates of a WinForm control from other classes

Could someone please help me with the following problem:

There are two classes MainForm and LWriter. Below is a method from the LWriter that in addition to writing to a file sends some updates to a RichTextBox control (through mainForm.UpdateLog(text)). Everything works fine, however, this WriteOutput method also does some extensive processing that during the calculation freezes the form.

I think the WriteOutput should be encapsulated in a separate thread. Could someone please help me out explaining how to place WriteOutput (LWriter class) in a thread that will then call mainForm.UpdateLog() from the mainFrom in a safe manner?

I am new to threads, thus help would be much appreciated.

public void WriteOutput(string output, Links[] links)
{
   try {
      using (StreamWriter sw = new StreamWriter(output)) {
         for (int x= 1; x<links.Length;x++) {
       ...
           sw.WriteLine( ... );
           sw.Flush();                              
         }
         mainForm.UpdateLog(<text>);
      }
   } catch(Exception e) { ... }
}
like image 240
Luke G Avatar asked Dec 09 '22 03:12

Luke G


2 Answers

Typically you should run this kind of time-consuming operations in a BackgroundWorker. Define a work method:

private void worker_DoWork(object sender, DoWorkEventArgs e)
{   
    // execute your WriteOutput method
}

and set is as the DoWork event handler:

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync(); // start the worker

To safely update the UI from a different thread use the Control.BeginInvoke method:

mainForm.BeginInvoke(
   () => { mainForm.UpdateLog(<text>); });
like image 128
Tudor Avatar answered Jan 04 '23 03:01

Tudor


As suggested by Sonu, delegate can be used for Thread safe calls, and you can use Linq to shorten the code:

this.BeginInvoke( (Action) delegate ()
{
       //code to update UI
});

See this link for more information.

like image 31
JulienVan Avatar answered Jan 04 '23 03:01

JulienVan