This is what I've always been wondered.
Suppose I've created a class named Agent, and the Agent does some
lengthy job. Of course I don't want to block the main window, so the
Agent does the job in a separate thread. If the job is progressed it
fires an event, and the main window handled the event by changing the
value of a progress bar. The problem is that this event is fired in
another thread so when the handler in the main window tries to access
the progress bar, an exception occurs. Until now, I've been solving
this problem by checking InvokeRequired and creating a delegate.
But the .NET 2.0's built-in BackgroundWorker seems to have solved this
with a very elegant way. When a BackgroundWorker fires the progress
event, it looks like the event is fired in the same thread as the main
window, because the InvalidOperationException does not occur when I
try to access UI controls in the handler. How could this be possible?
I want my Agent class to be able to the same thing. Making a lot of
delegations in the main window code makes the code dirty.
Please give me an idea. Thank you.