Background worker is working but not printing anything

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(); //both declared in the main Form
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

//Background worker
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 , , , . , , . .

+4
1

. BackgroundWorker , , .Invoke. , , .

WinForms :

this.ThreadSafeInvoke(() => logBox.WriteTimedLogLine("loop " + (i + 1).ToString()));

, .InvokeRequired bool true, Action, ThreadSafeInvoke .Invoke, .

, :

this.Invoke(new MethodInvoker(() => 
                logBox.WriteTimedLogLine("loop " + (i + 1).ToString())));

. , .

+4

Source: https://habr.com/ru/post/1623261/


All Articles