Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn’t BeginInvoke return reference of type AsyncResult?

Tags:

c#

.net

delegates

When you call a delegate object’s BeginInvoke, the system creates an object of type AsyncResult, but BeginInvoke returns a reference of type IAsyncResult interface ( which points to AsyncResult instance) . Why doesn’t BeginInvoke instead return a reference of type AsyncResult?

thanx

like image 343
AspOnMyNet Avatar asked Feb 28 '10 18:02

AspOnMyNet


2 Answers

This is standard interface based programming.

By returning an IAsyncResult, the framework is free to change the internal implementation at a later time, without breaking code written against the framework's API. This, in essence, telling us, as developers, that we should not care what type of implementation is used, provided the interface (IAsyncResult) is met.

If, instead, the actual AsyncResult class was returned, then changing to a different class would break existing code.

Also, this allows the framework to use the same interface (IAsyncResult) in multiple places, whether or not the AsyncResult class is appropriate. I've taken advantage of this, personally, as I've made my own asynchronous functions which return IAsyncResult backed by a different class, which stored the information which was important to me. This allows my own code to work like the framework, without restricting me to the framework's implementation.

like image 107
Reed Copsey Avatar answered Sep 19 '22 13:09

Reed Copsey


Because it doesn't always return an AsyncResult. The delegate target may exist in another execution context, a RealProxy derived class may implement a proxy for it. Remoting would be an example. Returning an interface type makes that transparent.

like image 45
Hans Passant Avatar answered Sep 17 '22 13:09

Hans Passant