I have seen others with a similar issue but not quite what I was looking for. In the backgrounderworker class dowork event I create an instance of a new class and call one of it's function. Previously, I had this code in a windows.form.timer tick event and would pass a delegate in as one of the parameters which would allow the function and other functions it calls within the class to call a method on the form to update a datagrid on the GUI. Is there a way to do this within the dowork event? I need this because the function I call from dowork calls other functions and I want each of those functions to log information in the GUI datagrid.
Apart from ReportProgess
mentioned in Hans' answer, you can alternatively use Control.Invoke on one of the UI elements to exeute code in the UI thread.
The BackgroundWorker.ReportProgress() method was intended to do that. You implement the ProgressChanged event to update the UI, it will run on the main thread. You're not restricted to report just a progress percentage, you can pass any object as well to pass info to the event handler by using the overload that accepts the userState argument. Beware that you have to use proper locking if you do that.
You can send progress data back to the UI thread, you will get an event for that on the UI thread, then you can update the screen. It is highly preferred that the objects you send back to the UI thread are immutable. Besides calling the ReportProgress
and handling the event you need to opt-in by setting WorkerSupportsProgress
property to true.