Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why we need EndInvoke() to return value of asynchronous call in delegate?

i am having a bit trouble in understanding it that BeginInvoke() method call in a delegate when asynchronously calls methods, after completion of it's tasks why can't BeginInvoke() itself return the return value from the method, why we require EndInvoke() to query BeginInvoke() and return the return value from it. i know this may be not a good query, but my confusion is real :-)

Addition: i can call a method asynchronously using DelagateName.BeginInvoke(parameters), now when the matching method in the delegate(suppose it returns a value) finishes it's work and returns a value, why i need DelegateName.EndInvoke() to get the returned value? why can't the first call itself can return value on method completion.

like image 417
mohits00691 Avatar asked Dec 18 '11 12:12

mohits00691


2 Answers

When BeginInvoke returns, the method hasn't finished - that's the whole point of it being asynchronous. So BeginInvoke can only give you a token representing the "promise" of a result at some point - and you use that promise to get the actual result using EndInvoke, usually in a callback.

In .NET 4 this is more pleasantly encapsulated using Task and Task<T> of course, but generics weren't part of .NET 1, hence the somewhat more convoluted approach for delegates.

like image 79
Jon Skeet Avatar answered Oct 18 '22 19:10

Jon Skeet


You only need the BeginInvoke and matching EndInvoke if you are wanting to call the delegate asynchronously i.e. it won't block the current thread. This is useful for long running methods or methods that call processes that you don't control e.g. across application boundaries.

From what you describe you may be better off using the Invoke method which will return the value within the same method - and on the same thread i.e. synchronously. Of course your thread could be blocked by a long running process in this instance. It depends what your are trying to do.

like image 20
Crab Bucket Avatar answered Oct 18 '22 20:10

Crab Bucket