Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Delegates

Tags:

c#

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?

like image 587
Filip Ekberg Avatar asked Feb 28 '23 07:02

Filip Ekberg


2 Answers

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.

like image 181
Jon Skeet Avatar answered Mar 11 '23 17:03

Jon Skeet


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

like image 29
Kirschstein Avatar answered Mar 11 '23 15:03

Kirschstein