I was trying to understand the evolution of delegates. And how best can this be understood than by understanding what came before it? I understand that the concept of delegates has come from function pointers in C++.
1. What is the primary reason for introducing the function pointers? Is it to support multi-threading?
Henk Holterman: Delegates / function-pointers exist to provide a level of flexibility. The selection of a method can be decoupled form its invocation.
I have been introduced to delegates while looking at this great threading resource
http://www.albahari.com/threading/
This is what Joe Albahari has to say about asynchronous delegates:
ThreadPool.QueueUserWorkItem
doesn’t provide an easy mechanism for getting return values back from a thread after it has finished executing. Asynchronous delegate invocations (asynchronous delegates for short) solve this, allowing any number of typed arguments to be passed in both directions. Furthermore, unhandled exceptions on asynchronous delegates are conveniently rethrown on the original thread (or more accurately, the thread that callsEndInvoke
), and so they don’t need explicit handling.
*2. Are all delegates asynchronous by nature?
Jon: A delegate is a pointer to code. It is not inherently either synchronous or asynchronous; the manner on which it is invoked and the result returned determines that.
Henk Holterman:When you have a delegate instance f you can synchronously call f() or you can call the asynchronous f.BeginInvoke()
- Is there any other uses of asynchronous delegates other than events?
dasblinkenlight: There are many uses of delegates in asynchronous APIs, for example, .NET Asynchronous I/O.
- How has the delegate/thread support in C# evolved over the versions?
*
dasblinkenlight: The core support of delegates remained the same, but the language added many important features to make it more convenient to define delegates.
C# 2.0: Introduction of anonymous delegates
C# 3.5: Added lambda expressions
C# 4.0: Added Task Parallel Library.
Edit: Most of my queries here have been clarified. If I could get a "history" for delegates and more practical usages for them, it would be great!