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) { ... }
}
Best Answer
Typically you should run this kind of time-consuming operations in a
BackgroundWorker
. Define a work method:and set is as the
DoWork
event handler:To safely update the UI from a different thread use the
Control.BeginInvoke
method: