为什么可以对同一个委托实例多次调用 BeginInvoke?
我认为在同一个委托实例上多次调用 BeginInvoke
会导致问题,但我尝试了一下,它有效。 这是为什么?
每个 BeginInvoke
调用时返回的 IAsyncResult
对象是否是唯一的,而不是每个委托实例?
换句话说,我是否只需要委托的一个实例来生成对其函数的多次调用?
I thought that calling BeginInvoke
more than once on the same delegate instance would cause problems, but I tried it out and it works. Why is that?
Is the IAsyncResult
object returned with each BeginInvoke
called unique instead of each instance of the delegate?
In other words, do I only need one instance of the delegate to spawn multiple calls to its function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
每次调用
BeginInvoke
都会触发 .net 线程池的新请求。多次调用
BeginInvoke
是完全可以接受的。每个IAsyncResult
对象对于BeginInvoke
的特定调用都是唯一的。请务必小心,确保对每次
BeginInvoke
调用都对EndInvoke
进行匹配的调用,以确保资源得到清理。(请注意,每个调用不一定等同于一个线程。
BeginInvoke
将请求传递到线程池,如果池中的所有线程都已在使用中,线程池可能会将请求排队)Each call to
BeginInvoke
triggers a new request onto the .net thread pool.It is perfectly acceptable to call
BeginInvoke
multiple times. EachIAsyncResult
object is unique to that specific call toBeginInvoke
.Just be careful to make sure that you make a matching call to
EndInvoke
for everyBeginInvoke
call you make to make sure the resources are cleaned up.(Note that each call does not necessarily equate to a thread.
BeginInvoke
passes the requests to the thread pool, which may queue up the requests if all of the threads in the pool are already in use)为什么它不起作用?每次调用它时,它将开始在线程池线程上执行该委托的操作。是的,每个
IAsyncResult
将独立于其他的,代表该异步操作。是的,您只需要一个委托实例。请注意,委托是不可变的 - 调用
BeginInvoke
不会更改其状态。您可以安全地获取委托引用的副本,因为调用Delegate.Combine
等将始终创建一个新委托实例,而不是修改现有委托实例。Why would it not work? Each time you call it, it will start executing that delegate's actions on a threadpool thread. Yes, each
IAsyncResult
will be independent of the others, representing that asynchronous action.Yes, you only need one instance of the delegate. Note that delegates are immutable - calling
BeginInvoke
isn't going to change its state. You can safely take a copy of a delegate reference, safe in the knowledge that callingDelegate.Combine
etc will always create a new delegate instance, rather than modifying the existing one.例如,您可能有多个线程调用同一个委托实例,因为您希望它们全部执行相同的任务。
You may have multiple threads calling the same delegate instance, as per you wish them all to perform the same task, for instance.
是的。
每次调用
BeginInvoke
都会返回不同的IAsyncResult
,该结果可以按任意顺序传递给EndInvoke
。您可以使用同一个委托进行多个异步调用。
Yes.
Each call to
BeginInvoke
will return a differentIAsyncResult
, which can be passed toEndInvoke
in any order.You can use the same delegate to make multiple asynchronous calls.