There are many ways to update your UI from async ThreadPool threads. This is just one of them; my preferred way of doing so.
These are my general purpose methods, in my base form class, for updating the UI from methods that are running on ThreadPool threads. Before you jump up and down and accuse me of bad exemption handling here though, perhaps I should point out that I typically call these from long-running methods, where all I want is a way to safely update the user interface, and I do not care about exceptions there. I’m trapping all the important exceptions elsewhere, and I have global “handlers” that log unhandled exceptions. Any exceptions from these simple methods will thus:
- If they are bugs, immediately be noticed by me in my log file. (Thus they never make it to the code of the released application.)
- Otherwise, they will almost certainly indicate the application was going down already, and they should be ignored. (Those will normally in any case be of type InvalidOperationException or ObjectDsposedException, which are silently ignored.)
Again, the source, for this and a whole bunch of other stuff, is here: RomyView.zip
All the overloads do the same thing: Call Task.Factory.StartNew with a captured SynchronizationContext. (Technically, actually a TaskScheduler with a captured SynchronizationContext.)
The overloads allow me to call this with or without supporting cancellation, and with or without expecting a return value. Here is all the code, copied and pasted together so that it is easier to follow.
An example where I use this can be found in my post entitled Concurrent asynchronous processing of all the files in a directory with support for cooperative pausing, in C#