为什么使用TEMPORARY引用引发事件? [英] Why to use TEMPORARY reference is event raising?

查看:158
本文介绍了为什么使用TEMPORARY引用引发事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!

我在班级有一个引发事件TextChanged 的方法

Hi everyone!

I have a method to raise an event TextChanged in my class

  protected virtual void OnTextChanged( EventArgs e )
{
   EventHandler  temp = this.TextChanged;

 if (temp != null)  
    // --- possible unscribing ---
    temp(this, e);

}



我知道在多线程应用程序中,有时还会有其他调用
NULL
之后,其他线程中的线程可能会从事件中取消注册 检查并在调用委托之前...
但是区别是什么?
TextChanged 是参考,temp 也是参考,
temp 指向TextChanged ,所以它指向TextChanged 指向
的同一内存块 如果TextChanged == nulltemp 也是NULL
请说明



I know that in multithreaded applications sometimes other calls
in other threads might unscribe from the event right after the NULL
check and before the invocation of delegate...
but what is the DIFFERENCE???
TextChanged is a reference and temp is also a reference and
temp points to TextChanged so it points to the same block of memory where TextChanged points
if TextChanged == null then temp is also NULL
Please explain

推荐答案

执行OnTextChanged方法时,TextChanged的当前值将加载到temp中:两者都指向同一个对象-已订阅的事件处理程序到TextChanged事件.

如果此后另一个线程取消订阅,则TextChanged可以为null.但是temp仍指原始事件处理程序. temp的值不变.然后,您可以测试温度,如果不为null,则发出事件信号.

如果您不复制TextChanged事件,则测试可以通过,但是另一个线程可以在测试和执行之间更改TextChanged.不太可能,但是有可能.
When you execute the OnTextChanged method, the current value of TextChanged is loaded into temp: both are referring to the same object - an event handler that has subscribed to the TextChanged event.

If after this, another thread unsubscribes, then TextChanged can become null. But temp is still referring to the original event handler. The value of temp does not change. You can then test temp, and if not null, signal the event.

If you didn''t take a copy of the TextChanged event, then the test could pass, but another thread could then change TextChanged between the test and the execute. It is unlikely, but it is possible.


这篇关于为什么使用TEMPORARY引用引发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆