简体   繁体   中英

Do I need to implement a background worker

I have a main GUI application, that does all of it's actual work in a referenced assembly. Right now, I DON'T do the work in a background worker, so it basically locks the main UI while it does it's processing. In my referenced assmbly, I added quite a few events to report back different progress back to the main UI form. On the main UI form, I update different text boxes with the values from those events. My question is, first of all, the processing appears to be much slower when throwing these events. So should I fire the events on a secondary thread (from the referenced assembly)? Should my original call to the referenced (static) assmebly be via a background worker? I'd like to report the different types of progress on a separate thread, just not sure which approach to take to have optimal performance.

Thanks

From your description it sounds like you would benefit from multithreading, as it would help keep the UI responsive.

And the easiest way to do this is to use a BackgroundWorker. Start by working through one of the many samples , then bite the bullet, and come back here if you have any problems.

In response to comment:

The best way to communicate from a BackgroundWorker worker thread to the main thread is to call the BackgroundWorker.ReportProgress method, which takes an optional object parameter userState which you can use to package up the data you want to communicate.

This causes the BackgroundWorker.ProgressChanged event to be raised on the main thread - and the data can be processed without the need for an explicit Invoke .

If you've already implemented events, you'll either have to do some rework to call ReportProgress instead of raising events, or implement some kind of adapter to handle the events and route them to ReportProgress method calls.

You could launch your process (the method on the other assembly) on a different thread, and handle the events raised by it on the main form.

Since the UI cannot be updated by another thread, you should wrap the code of those events on a this.Invoke().

Ex:

private void TheEventRaisedOnAnotherThread(object sender, EventArgs e)
{
    _counter++;
    this.Invoke(new MethodInvoker(delegate() { TextBox1.Text = _counter.ToString(); }));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM