Click here to Skip to main content
16,017,788 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone!

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

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

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

}


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
Posted
Updated 27-Apr-10 5:04am
v2

1 solution

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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900