简体   繁体   中英

Why AsyncCallback?

I have read that the AsyncCallback function will do all the post processing tasks after a delegate call completes. My question is what is the difference of writing the post processing tasks after/below EndInvoke , as EndInvoke will wait until the delegate call returns.

The point of using a delegate's BeginInvoke() method is that the target will run asynchronously. If you call EndInvoke() right after BeginInvoke() then there is no longer any point in using it. You'll get the exact same behavior by simply calling the delegate directly, minus the overhead and the threading headaches.

The value is getting the callback when the target method completes, asynchronously right after it does. Only then call EndInvoke(), it completes immediately. That cleans up the system resources and re-throws an exception when the target method threw one. Do not skip calling EndInvoke() as suggested in the upvoted answer, you'll leak the resources for at least 10 minutes.

You could choose not to invoke EndInvoke at all and only rely on the callback. This way the initiation comes from the delegate itself and not from you, and you dont have to decide when the invocation will complete.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM