调用事件处理程序
我有以下事件处理程序:
private EventHandler<MyEventArgs> _myEventHandler;
public event EventHandler<MyEventArgs> MyEvent
{
add { _myEventHandler += value; }
remove { _myEventHandler -= value; }
}
有人可以解释以下片段之间的区别吗?
代码段 EventHandler (A):
//Snippet A:
if (_myEventHandler != null)
{
_myEventHandler(new MyEventArgs());
}
代码段 BeginInvoke (B):
//Snippet B:
if (_myEventHandler != null)
{
_myEventHandler.BeginInvoke(new MyEventArgs(), ar =>
{
var del = (EventHandler<MyEventArgs>)ar.AsyncState;
del.EndInvoke(ar);
}, _myEventHandler);
}
澄清一下:“按原样”调用 EventHandler 与使用 BeginInvoke
之间有什么区别?
I have the following EventHandler:
private EventHandler<MyEventArgs> _myEventHandler;
public event EventHandler<MyEventArgs> MyEvent
{
add { _myEventHandler += value; }
remove { _myEventHandler -= value; }
}
Could somebody explain the difference between the following snippets?
Snippet EventHandler (A):
//Snippet A:
if (_myEventHandler != null)
{
_myEventHandler(new MyEventArgs());
}
Snippet BeginInvoke (B):
//Snippet B:
if (_myEventHandler != null)
{
_myEventHandler.BeginInvoke(new MyEventArgs(), ar =>
{
var del = (EventHandler<MyEventArgs>)ar.AsyncState;
del.EndInvoke(ar);
}, _myEventHandler);
}
For clarification: What's the difference between invoking an EventHandler "just as it is" and using BeginInvoke
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
BeginInvoke
方法是异步的,这意味着它是在不同的线程上引发的。如果人们没有预料到,这可能会很危险,而且对于事件来说非常罕见 - 但它可能很有用。另外,请注意,严格来说,您应该对事件处理程序值进行快照 - 如果(通过
Begin*
)您正在处理线程,则尤其如此。 。另请注意,您的事件订阅本身不是线程安全的;再次强调,这仅在您处理多线程时才重要,但是内置的类似字段的事件是线程安全的:
这里避免的问题是:
The
BeginInvoke
approach is async, meaning that it is raised on a different thread. This can be dangerous if people don't expect it, and is pretty rare for events - but it can be useful.Also, note that strictly speaking you should snapshot the event handler value - this is especially true if (via
Begin*
) you are dealing with threads.Also - note that your event subscription itself is not thread-safe; again, this only matters if you are dealing with multi-threading, but the inbuilt field-like event is thread-safe:
The issues avoided here are:
BeginInvoke()
调用立即将控制权返回给调用线程,并在与ThreadPool
不同的线程中运行委托,因此这将是某种异步执行。BeginInvoke()
call immediatelly returns control to the calling thread and run a delegate in a separate thread from theThreadPool
, so this will be some kind of asynchronous execution.