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
- Create BackgroundWorker and appoint doWork_fetchData() method to the doWork event
- Call the Async method of my Worker instance
- Have the ListView updated without the User Interface beeing “frozen” during download of data.
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
BackgroundWorkercommunicates with the UI thread usingReportProgress. 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 yourListView.The other alternative in Windows Forms is to call
Control.InvokeorControl.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,InvokeandBeginInvoke. You can access the dispatcher for a control with theDispatcherproperty.