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) { ... }
}
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>); });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With