Click here to Skip to main content
15,886,873 members
Articles / Desktop Programming / Windows Forms

Implementing an event which supports only a single event handler, in C#

Rate me:
Please Sign up or sign in to vote.
3.74/5 (6 votes)
30 Nov 20052 min read 62.3K   759   18  
This article demonstrates how to implement an event, for which at a given point of time only one client can subscribe to. If multiple clients subscribe to the same event (of the same object), only the client subscribing last will get the event notification.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

/// <summary>
/// The following sample demonstrates how to implement a 
/// event which works like single cast, ie it will support 
/// only one handler to be subscribed to this event.
/// By default Events exhibit multicast behavior, ie when the 
/// event is raised all the clients who have subscribed to this 
/// event will receive the notification one after the other. 
/// But in this example only the client who has subscribed 
/// the event last will get the notification.
/// This case holds good when we have multiple threads subscribing 
/// for a notification, but it is enough if it is been processed 
/// by one thread, in this case the event may 
/// not be sent to all the thread. 
/// </summary>

/// <Author>
/// Madhu Raykar
/// </Author>
/// 
/// <Date>
/// 30 Nov 2005
/// </Date>

namespace SinglecastEvent
{
	public class frmSingleCast : System.Windows.Forms.Form
	{
        private System.Windows.Forms.GroupBox grpMessages;
        private System.Windows.Forms.GroupBox grpSubscribe;
        private System.Windows.Forms.GroupBox grpRaiseEvent;
        private System.Windows.Forms.TextBox txtMessages;
        private System.Windows.Forms.Button btnClient1;
        private System.Windows.Forms.Button btnClient2;
        private System.Windows.Forms.Button btnRaiseEvent;
		private System.ComponentModel.Container components = null;
        private EventRaiser eventRaiser = new EventRaiser();

		public frmSingleCast()
		{
			InitializeComponent();
		}

		#region Windows Form Designer generated code
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing ) {
            if( disposing ) {
                if (components != null) {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        
        /// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.grpMessages = new System.Windows.Forms.GroupBox();
            this.grpSubscribe = new System.Windows.Forms.GroupBox();
            this.grpRaiseEvent = new System.Windows.Forms.GroupBox();
            this.txtMessages = new System.Windows.Forms.TextBox();
            this.btnClient1 = new System.Windows.Forms.Button();
            this.btnClient2 = new System.Windows.Forms.Button();
            this.btnRaiseEvent = new System.Windows.Forms.Button();
            this.grpMessages.SuspendLayout();
            this.grpSubscribe.SuspendLayout();
            this.grpRaiseEvent.SuspendLayout();
            this.SuspendLayout();
            // 
            // grpMessages
            // 
            this.grpMessages.Controls.Add(this.txtMessages);
            this.grpMessages.Location = new System.Drawing.Point(8, 92);
            this.grpMessages.Name = "grpMessages";
            this.grpMessages.Size = new System.Drawing.Size(424, 104);
            this.grpMessages.TabIndex = 0;
            this.grpMessages.TabStop = false;
            this.grpMessages.Text = "Messages";
            // 
            // grpSubscribe
            // 
            this.grpSubscribe.Controls.Add(this.btnClient2);
            this.grpSubscribe.Controls.Add(this.btnClient1);
            this.grpSubscribe.Location = new System.Drawing.Point(8, 3);
            this.grpSubscribe.Name = "grpSubscribe";
            this.grpSubscribe.Size = new System.Drawing.Size(256, 80);
            this.grpSubscribe.TabIndex = 1;
            this.grpSubscribe.TabStop = false;
            this.grpSubscribe.Text = "Subscribe";
            // 
            // grpRaiseEvent
            // 
            this.grpRaiseEvent.Controls.Add(this.btnRaiseEvent);
            this.grpRaiseEvent.Location = new System.Drawing.Point(280, 3);
            this.grpRaiseEvent.Name = "grpRaiseEvent";
            this.grpRaiseEvent.Size = new System.Drawing.Size(152, 80);
            this.grpRaiseEvent.TabIndex = 2;
            this.grpRaiseEvent.TabStop = false;
            this.grpRaiseEvent.Text = "RaiseEvent";
            // 
            // txtMessages
            // 
            this.txtMessages.Location = new System.Drawing.Point(8, 16);
            this.txtMessages.Multiline = true;
            this.txtMessages.Name = "txtMessages";
            this.txtMessages.ReadOnly = true;
            this.txtMessages.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.txtMessages.Size = new System.Drawing.Size(400, 80);
            this.txtMessages.TabIndex = 0;
            this.txtMessages.Text = "";
            // 
            // btnClient1
            // 
            this.btnClient1.Location = new System.Drawing.Point(18, 24);
            this.btnClient1.Name = "btnClient1";
            this.btnClient1.Size = new System.Drawing.Size(101, 40);
            this.btnClient1.TabIndex = 0;
            this.btnClient1.Text = "Client 1";
            this.btnClient1.Click += new System.EventHandler(this.btnClient1_Click);
            // 
            // btnClient2
            // 
            this.btnClient2.Location = new System.Drawing.Point(138, 24);
            this.btnClient2.Name = "btnClient2";
            this.btnClient2.Size = new System.Drawing.Size(101, 40);
            this.btnClient2.TabIndex = 1;
            this.btnClient2.Text = "Client 2";
            this.btnClient2.Click += new System.EventHandler(this.btnClient2_Click);
            // 
            // btnRaiseEvent
            // 
            this.btnRaiseEvent.Location = new System.Drawing.Point(24, 24);
            this.btnRaiseEvent.Name = "btnRaiseEvent";
            this.btnRaiseEvent.Size = new System.Drawing.Size(101, 40);
            this.btnRaiseEvent.TabIndex = 0;
            this.btnRaiseEvent.Text = "Raise Event";
            this.btnRaiseEvent.Click += new System.EventHandler(this.btnRaiseEvent_Click);
            // 
            // frmSingleCast
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(442, 208);
            this.Controls.Add(this.grpRaiseEvent);
            this.Controls.Add(this.grpSubscribe);
            this.Controls.Add(this.grpMessages);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.Name = "frmSingleCast";
            this.Text = "Single Cast Event";
            this.grpMessages.ResumeLayout(false);
            this.grpSubscribe.ResumeLayout(false);
            this.grpRaiseEvent.ResumeLayout(false);
            this.ResumeLayout(false);

        }
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
 			Application.Run(new frmSingleCast());
        }


        private void btnClient1_Click(object sender, System.EventArgs e) {        
            txtMessages.Text += "Client 1 subscribed to event, other clients will stop listening to event. " + Environment.NewLine;
            // Simulate that client 1 is subscribing to the OnRaiseEvent of EventRaiser class
            eventRaiser.OnRaiseEvent += new EventHandler(Client1_OnRaiseEventHandler);
        }

        private void btnClient2_Click(object sender, System.EventArgs e) {
            txtMessages.Text += "Client 2 subscribed to event, other clients will stop listening to event." + Environment.NewLine; 
            // Simulate that client 2 is subscribing to the OnRaiseEvent of EventRaiser class
            eventRaiser.OnRaiseEvent += new EventHandler(Client2_OnRaiseEventHandler);
        }

        private void Client1_OnRaiseEventHandler(object sender, EventArgs e)
        {
            // This is client 1's handler for the event
            txtMessages.Text += "Client 1 : event received." + Environment.NewLine; 
        }
        
        private void Client2_OnRaiseEventHandler(object sender, EventArgs e) 
        {
            // This is client 2's handler for the event
            txtMessages.Text += "Client 2 : event received." + Environment.NewLine; 
        }

        private void btnRaiseEvent_Click(object sender, System.EventArgs e) {
            eventRaiser.RaiseEvent();
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
India India
I have been working in software industry for the past 5 years now. Enjoy working on complex and new technologies. Worked on Microsoft technologies Like VC++, COM, XML, SQL. Currently working on .Net, C#.

Comments and Discussions