Why do we need EndInvoke () to return the value of an asynchronous call in the delegate?

I have a little problem understanding that the BeginInvoke () method calls a delegate when calling methods asynchronously, after completing its tasks, why BeginInvoke () cannot return the return value from the method, why we require EndInvoke () for the BeginInvoke () request and return the return value from it. I know this may not be a very good request, but my confusion is real :-)

Addition: I can call the method asynchronously using DelagateName.BeginInvoke (parameters), now that the matching method in the delegate (suppose that it returns a value) completes and returns a value, why do I need DelegateName.EndInvoke () to get the return value? why the first call cannot return a value when the method ends.

+6
source share
2 answers

When BeginInvoke returns, the method is not finished yet - all its asynchrony. That way, BeginInvoke can only give you a token representing a β€œpromise” of the result at some point β€” and you use that promise to get the actual result with EndInvoke , usually in a callback.

In .NET 4, this is more nicely encapsulated using Task and Task<T> , but generics were not part of .NET 1, hence a somewhat more confusing approach for delegates.

+8
source

You only need BeginInvoke and the corresponding EndInvoke if you want to invoke the delegate asynchronously, i.e. it will not block the current thread. This is useful for long-running methods or methods that call processes that you do not control, for example. across application boundaries.

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

+8
source

Source: https://habr.com/ru/post/904022/


All Articles