Just to showcase multiple features of delegates in a single function :) This can be used to have a concise feature set of delegates
Problem statement: Using multicast delegates asynchronously to update a winform control using lambda expression
Problem elaboration
- delegate
- - that too multicast
- async invocation
- winform control update (threading issue)
Seems complicated ??
Not so much :) The example illustrates all the features available in delegate usage in .NET 3.5
public void DelegateTest ()
{
Func<int, int> myDelegate;
myDelegate = (i) => { return ++i; };
myDelegate += (i) => { return i; };
myDelegate += (j) => { return --j; };
Action<int> textboxWrite = (delRes) => { textBox1.Text += " " + delRes.ToString(); };
foreach (var d in myDelegate.GetInvocationList())
{
var myDel = d as Func<int, int>;
myDel.BeginInvoke(0,
res =>
{
var result = myDel.EndInvoke(res);
textBox1.BeginInvoke(textboxWrite, new object[] { result });
}, null);
}
}
Now the internals
- A delegate in .NET is multicast since it can hold references to multiple functions . These get added to the internally managed "InvocationList" which is a collection of delegates of the same type. Each function gets executed in sequence of adding.
- Func and Action are specific delegates
Func provides a return value
Action does not provides a return value
- Lambda expressions are 3.5 feature over previous anonymous functions (2.0 stuff)
- Updating a winform control from non-owner thread requires a hold of the UI thread, using BeginInvoke. The UI thread is hyper performance intensive, so no other thread is given permission to mingle in its job.
I am a solutions lead working on .NET for about 10 years, focusing on core framework implementations in project. My development interests are in middle tier and backend components and sometimes, identifying design elements for technical solutions. Apart, I collect coins and stamps and do photography whenever I get a chance.