It's not the first time I come across delegates and I am as confused as I were the last time and the time before that. So once and for all I want to get the delgate-confusion cleared up.
My problem is as followed
Having a Graphical User Interface which only displays a ListView with some boud items, I want to load the data from a Data Connection which takes some time, to increase the comfort of using the application I have instancieted a BackgroundWorker and in the doWork-method I want to fetch the data and display it.
This is how I want it
Now this is Cross-Thread-Invoking and I wanted to solve this with Delegates which brings me here. Following this tutorial, I got a working Delegate, However it did not solve the problem, inside my delegate I cannot change my ListView, it still says it is on another thread.
I want to find an Easy explenation on delegates and how to use them to solve my problem. Also, should I think or design my software different?
Normally BackgroundWorker
communicates with the UI thread using ReportProgress
. You would hook up a delegate to receive those progress events before launching the background worker, and then the progress would be reported on the UI thread, where you're safe to change your ListView
.
The other alternative in Windows Forms is to call Control.Invoke
or Control.BeginInvoke
, passing in a delegate which will update the UI. That delegate will be executed on the UI thread. For an example of this, see my threading tutorial or Joe Albahari's.
The equivalent of this in WPF is the Dispatcher
- again, Invoke
and BeginInvoke
. You can access the dispatcher for a control with the Dispatcher
property.
You can't change a ui control from a different thread directly, you need to check the Control.InvokeRequired
property before you make a change.
See this example on msdn
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With