I have BackgroundWorker, called bgw, to which I pass my custom Form, called LogBoxFormto. A custom job Formis just typing something on it.
LogBoxForm logBox = new LogBoxForm();
BackgroundWorker bgw = new BackgroundWorker();
In the main Form Load eventtwo events were initiated bgw: DoWorkand RunWorkerCompletedhow this
bgw.DoWork += bgw_DoWork;
bgw.RunWorkerCompleted += bgw_RunWorkerCompleted;
And then, when I clicked Buttonwith the name button9, it bgwwill be launched as indicated by this code
BackgroundWorker bgw = new BackgroundWorker();
private void button9_Click(object sender, EventArgs e) {
if (bgw.IsBusy)
return;
bgw.RunWorkerAsync(logBox);
}
void bgw_DoWork(object sender, DoWorkEventArgs e) {
LogBoxForm lbf = e.Argument as LogBoxForm;
try {
for (int i = 0; i < 5; ++i) {
lbf.WriteTimedLogLine("loop " + (i + 1).ToString());
Thread.Sleep(1000);
}
} catch (Exception exc) {
throw exc;
}
}
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
logBox.WriteTimedLogLine("Completed!");
if (e.Error != null)
logBox.WriteTimedLogLine(e.Error.ToString());
}
It stops at the line. catchThis is the error message I receive:
System.InvalidOperationException: cross-thread operation is not valid: The "richTextBoxAll" control is carried out from a stream other than the stream it was created on.
BackgroundWorker , , , . , , . .