Hello,
can somebody please explain me what delegates are and where they are useful?
Printable View
Hello,
can somebody please explain me what delegates are and where they are useful?
hehehe
I've been working with delegates for while now - its a requirement in .NET 2.0 especially if you are making cross threading calls.
The link Hack gave i believe will be good for your, it will be hard to grasp but will eventually get the hang of it.
Let me explain in .NET 2.0 terms
say you have a UI. in this UI there is a listbox.
you have made a thread in your program which, for example, populates list items into the listbox.
in .NET 1.1 this was fine to do. However there was a performance decrease well actually, it wasnt as safe threading as it would cause the UI sometimes (especially for mobile applications) to hang up and never respond.
.NET 2.0 had a cross-threading checker. if you call a component from a thread which it was not created in, you will get an invalidoperationexception - this example will state that you are making illegal cross threading calls.
how do we avoid this and do it the proper way? Doing it this way, is a GOOD Microsoft recommendation, as well as myself and i believe it is the only correct way of doing it - my opinion.
you make a delegate on the main class which has the features you want to access.
you make a method which is invoked upon from another thread.
example:
Code:
#region Public delegate variables
public void DoHandleAddListBoxItem(string theItemToAdd);
#endregion
#region The Delegate/Invoking methods
public void DoAddItemToListBox(string theItemToAdd);
{
if (this.InvokeRequired)
{
DoHandleAddListBoxItem myDelegate = new DoHandleAddListBoxItem(DoAddItemToListBox);
this.Invoke(myDelegate, new object[] { theItemToAdd };
}
else
{
this.listbox1.Items.Add(theItemToAdd);
}
}
#endregion
//..
//..
//somewhere here will be the code you call from another thread:
this.theMainUIClass.DoAddItemToListBox("adding item to listbox from a different thread");
//..
//..
This will make the UI responsive and not hang up and will not decrease performance as it has to then go outside of one thread, go into the main thread, do its stuff, then go back etc.....
Delegates are also useful for other various reasons - A class may not need to, does not need to know what other class to call to do some operation or whatever, therefore a delegate and method is made which this class, class A, can call without worrying about who to call in which class.
I hope this makes sense but im sure Hack's link is much better. But the code I have posted here as an example is the code used to invoke a control/method from a thread which this control/method was not created within!
thanks
Here's a article that's also worth reading.
Anonymous methods will really bake your noodle.
Also see "Predicates".