Events add and remove with synchronized block : event « GUI Windows Forms « C# / CSharp Tutorial






using System;
using System.Collections;
using System.Runtime.CompilerServices;
public class Button
{
    public delegate void ClickHandler(object sender, EventArgs e);
    
    Hashtable delegateStore = new Hashtable();
    static object clickEventKey = new object();
    
    public event ClickHandler Click
    {
        [MethodImpl(MethodImplOptions.Synchronized)]
        add
        {
            delegateStore[clickEventKey] =
            Delegate.Combine((Delegate) delegateStore[clickEventKey],
            value);
        }
        
        [MethodImpl(MethodImplOptions.Synchronized)]
        remove
        {
            delegateStore[clickEventKey] =
            Delegate.Remove((Delegate) delegateStore[clickEventKey],
            value);
        }
    }
    
    protected void OnClick()
    {
        ClickHandler ch = (ClickHandler) delegateStore[clickEventKey];
        if (ch != null)
        ch(this, null);
    }
    
    public void DoClick()
    {
        OnClick();
    }
}

class MainClass
{
    static public void ButtonHandler(object sender, EventArgs e)
    {
        Console.WriteLine("Button clicked");
    }
    
    public static void Main()
    {
        Button button = new Button();
        
        button.Click += new Button.ClickHandler(ButtonHandler);
        
        button.DoClick();
        
        button.Click -= new Button.ClickHandler(ButtonHandler);
        
        button.DoClick();
    }
}
Button clicked








23.64.event
23.64.1.Events
23.64.2.Using Event Accessors
23.64.3.Event and event handler
23.64.4.Use delegate to handle events
23.64.5.Fire event in property setter
23.64.6.Events: add and remove functions for a private delegate event
23.64.7.Events: add and remove functions
23.64.8.Events add and remove with synchronized block
23.64.9.Events: Custom Add and Remove with Global delegate cache.
23.64.10.A .NET-compatible event
23.64.11.Use the built-in EventHandler delegate
23.64.12.Use an anonymous method as an event handler
23.64.13.Ignored Parameters Anonymous Methods for Button click, kepressed and mouse clicked action
23.64.14.Events and form controls