Is EndInvoke() optional, sort-of optional, or defi

2020-01-24 07:11发布

I've read conflicting opinions as to whether every BeginInvoke() has to be matched by an EndInvoke(). Are there any leaks or other problems associated with NOT calling EndInvoke()?

7条回答
啃猪蹄的小仙女
2楼-- · 2020-01-24 07:14

Delegate.EndInvoke is documented as a thou shalt call this (i.e. necessary - else leaks happen) - from msdn:

Important Note

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

Control.EndInvoke is OK to ignore for fire-and-forget methods - from msdn:

You can call EndInvoke to retrieve the return value from the delegate, if neccesary, but this is not required.

However - if you are using Delegate.BeginInvoke and don't want the result, consider using ThreadPool.QueueUserWorkItem instead - it'll make life a lot easier, and avoid the pain of IAsyncResult etc.

查看更多
一夜七次
3楼-- · 2020-01-24 07:15

It is not optional because calling BeginInvoke makes use of a WaitHandle which in turns makes use of a kernel object that maintains a count for how many references are had to it. Calling EndInvoke gracefully disposes the handle which decrements that counter on the kernel object and when that count reaches zero, the kernel object manager will destroy it.

查看更多
趁早两清
4楼-- · 2020-01-24 07:22

Every reply on this post says that EndInvoke() is not optional. However, I found the following highly ranked comment that is the accepted answer on this SO thread:

"Note that the Windows Forms team has guaranteed that you can use Control.BeginInvoke in a 'fire and forget' manner - i.e. without ever calling EndInvoke. This is not true of async calls in general: normally every BeginXXX should have a corresponding EndXXX call, usually in the callback."

What's the difference between Invoke() and BeginInvoke()

查看更多
淡お忘
5楼-- · 2020-01-24 07:23

Its only optional if you don't mind your program's memory growing very large. The issue is that the GC is holding onto all of the references in your thread, because you might want to call EndInvoke at some point. I would go with Marc's answer, the threadpool will make your life easier. However, you need to watch out if you spawn threads from your threads, as it is limited in the number of threads it can spin up.

查看更多
【Aperson】
6楼-- · 2020-01-24 07:25

EndInvoke is not optional.

More info here

查看更多
虎瘦雄心在
7楼-- · 2020-01-24 07:25

EndInvoke is not optional because it is the place where exceptions are thrown if something went wrong in the asyncronous processing.

Anyway there should not be any leak because if the IAsyncResult is holding some native resource it should correctly implement IDisposable and dispose such resources when the GC calls his finalizer.

查看更多
登录 后发表回答