开发者

What exactly does Delegate.EndInvoke do? Is it necessary to call? [duplicate]

开发者 https://www.devze.com 2023-04-07 11:36 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Why does asynchronous delegate method require calling EndInvoke?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Why does asynchronous delegate method require calling EndInvoke?

Is Delegate.EndInvoke() really necessary?

Working on a multi-threaded application at the moment and when raising an event instead of doing the normal handler.Invoke(); I am experimenting with handler.BeginInvoke();. Both work fine. However, for BeginInvoke I am using null for the last two arguments because there needs not be a callback and since there is no callback, there is definitely no need for data to be passed to a non-existent callback.

Because of this, I am not calling EndInvoke at all. But the application seems to.. work perfectly? I read and people said there would be leaks which may be occurring but I am just not noticing.

I'm curious though, what exactly does EndInvoke do? Do I really need to make a callback just to call EndInvoke and that's it? Also, why does EndInvoke take an IAsyncResult argument? I can just pass null for that right because there is no extra data being passed to the callback, correct? But still, I'm wondering, why, if there was extra data, would it need to be passed to EndInvoke? What is it doing with that parameter? I wa开发者_如何学运维nt to know how it works.

I checked the .NET Reflector but I couldn't find where EndInvoke was actually defined. In EventHandler (which is what I'm using) all it showed was the method header.

Thanks.


The main practical concerns are deterministically cleaning up a wait handle resource (if you chose to create the handle by referencing it) and making sure that Exceptions are propagated properly.

That said, what I would recommend is to move away from the slightly schizophrenic asynchronous pattern in the earlier .NET framework and use TPL, which has a much cleaner continuation model. The TPL even has some nice wrapping functionality to help deal with the older Begin/End style of calling:

http://msdn.microsoft.com/en-us/library/dd997423.aspx


As was mentioned in one of the referenced articles, if you're invoking a delegate in a fire-and-forget fashion, you probably should use ThreadPool.QueueUserWorkItem instead. Then you won't have to worry about cleaning up with EndInvoke.


According to MSDN, you ought to always call EndInvoke no matter what:

No matter which technique you use, always call EndInvoke to complete your asynchronous call.

So take that for what it's worth. I assume it's futureproofing.

0

精彩评论

暂无评论...
验证码 换一张
取 消