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()
dasblinkenlight: There are many uses of delegates in asynchronous APIs, for example, .NET Asynchronous I/O.
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!
The primary reason for introducing delegates is to provide a mechanism for manipulating snippets of executable code: storing pointers to it, passing to functions, organize in data structures, and so on.
Like all function invocations, invoking an individual delegate is synchronous, in the sense that the caller must wait for the delegate to finish before getting the control back. However, you can use delegates to implement asynchronous APIs by passing a piece of code that could be stored and executed later on (asynchronously).
There are many uses of delegates in asynchronous APIs, for example, .NET Asynchronous I/O.
The core support of delegates remained the same, but the language added many important features to make it more convenient to define delegates. For example, C#2.0 added anonymous delegates, and C#3.5 added lambdas.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With