Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid duplicate event subscriptions in C#

How would you suggest the best way of avoiding duplicate event subscriptions? if this line of code executes in two places, the event will get ran twice. I'm trying to avoid 3rd party events from subscribing twice.

theOBject.TheEvent += RunMyCode;

In my delegate setter, I can effectively run this ...

theOBject.TheEvent -= RunMyCode;
theOBject.TheEvent += RunMyCode;

but is that the best way?

like image 700
ScottCate Avatar asked May 03 '09 17:05

ScottCate


2 Answers

I think, the most efficient way, is to make your event a property and add concurrency locks to it as in this Example:

private EventHandler _theEvent;
private object _eventLock = new object();
public event EventHandler TheEvent
{
    add
    {
        lock (_eventLock) 
        { 
            _theEvent -= value; 
            _theEvent += value; 
        }
    }
    remove
    {
        lock (_eventLock) 
        { 
           _theEvent -= value; 
        }
    }
}
like image 66
Jose Basilio Avatar answered Oct 01 '22 01:10

Jose Basilio


I have done this before....it assumes it is acceptable that the last subscriber is what gets called.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            MyObject my = new MyObject();
            my.Changed += new EventHandler(my_Changed);
            my.Changed += new EventHandler(my_Changed1);

            my.Update();
            Console.ReadLine();
        }

        static void my_Changed(object sender, EventArgs e)
        {
            Console.WriteLine("Hello");
        }
        static void my_Changed1(object sender, EventArgs e)
        {
            Console.WriteLine("Hello1");
        }
    }
    public class MyObject
    {
        public MyObject()
        {
        }
        private EventHandler ChangedEventHandler;
        public event EventHandler Changed
        {
            add
            {
                ChangedEventHandler = value;
            }
            remove
            {
                ChangedEventHandler -= value;
            }
        }
        public void Update()
        {
            OnChanged();
        }

        private void OnChanged()
        {
            if (ChangedEventHandler != null)
            {
                ChangedEventHandler(this, null);
            }
        }
    }
}
like image 29
joeln Avatar answered Sep 30 '22 23:09

joeln