[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

How to check if already subscribed to event?

Posted on 2009-04-29
15
Medium Priority
?
534 Views
Last Modified: 2012-05-06
I have a .NET 3.5 winforms app with the following:

public class Class1{
....
myInstance.TheEvent += new EventHandler (myInstance_TheEvent);
...
}

The above is in a method that might be called more than once.  I can't put the above in Class1's constructor because myInstance isn't created at that time.  There's a particular workflow that is followed, which causes myInstance to be created after the constructor call.  I'd like to check if

myInstance.TheEvent == null

and subscribe only for that case.  However, that conditional is not legal.  How else can I check if myInstance has already subscribed to TheEvent?
0
Comment
Question by:brettr
  • 7
  • 7
15 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 24266152
Wherever in your code that you raise the event, that is where you check for null:
public class Test
{
    private string testString;
    public event EventHandler TestEvent;
 
    public Test()
    {
        this.testString = string.Empty;
    }
 
    public string TestProperty
    {
        get
        {
            return this.testString;
        }
 
        set
        {
            this.testString = value;
 
            if (this.TestEvent != null)
            {
                this.TestEvent(this, new EventArgs());
            }
        }
    }
}

Open in new window

0
 

Author Comment

by:brettr
ID: 24266205
There are many other subscribers so that will not handle this particular instance.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 24266245
The event is not marked static, so there is a separate event for each instance of the class. Perhaps I'm not following what you are referring to.
0
Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

 
LVL 15

Expert Comment

by:JackOfPH
ID: 24267477
I don't know how in C# but in vb this is what I usually do...

If not me.TestEvent is  nothing then

end if

or

If not me.Testevent is system.dbnull.value then

end if


I hope you get my idea...

0
 

Author Comment

by:brettr
ID: 24269813
@kaufmed

Ok, sorry.  The event is in a singleton.  So, it will have multiple subscribers.

@JackOfPH

That's was my initial approach.  Unfortunately, C# will complain about that type of checking, as mentioned above.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 24270060
Would exposing another property work:
public bool IsWired
{
    get { return (this.OnEvent != null); }
}
 
 
// Consumer
 
if (!class.IsWired)
{
    class.Event += new EventHandler();
}

Open in new window

0
 

Author Comment

by:brettr
ID: 24270251
No because again, this is in a singleton.  this.OnEvent might have 10 different subscribers, where the above Class1 is #10.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 24270646
Ok, I'm not trying to be thick, I've just never written my own singleton.

What if you did something like such (where you raise the private event in code--the public event is just for checking the list):
private List<EventHandler> subscribedEvents;
private event EventHandler _OnEvent;
public event EventHandler OnEvent
{
    add
    {
        if (!this.subscribedEvents.Contains(value))
        {
            this._OnEvent += value;
            this.subscribedEvents.Add(value);
        }
    }
    remove
    {
        if (this.subscribedEvents.Contains(value))
        {
            this._OnEvent -= value;
            this.subscribedEvents.Remove(value);
        }
    }
}

Open in new window

0
 

Author Comment

by:brettr
ID: 24275350
@kaufmed:
When I try your code, I can no longer raise the event:

private void onEventRaise()
        {
            if (OnEvent!= null)
            {
                OnEvent(this, new EventArgs());
            }
        }

I get this compiler error:

The event 'OnEvent' can only appear on the left hand sie of += or -=

Is there another way to raise it?
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 24275413
I don't see anything that relates to that error message in the code you posted. Is that the code that is highlighted by compiler when error occurs?
0
 

Author Comment

by:brettr
ID: 24275443
Yes.  It highlights these two lines:

if (OnEvent!= null)
            {
                OnEvent(this, new EventArgs());
0
 

Author Comment

by:brettr
ID: 24275467
Create a console app and paste the following into it to see the error:
namespace ConsoleApplication1
{
    class Class1
    {
        static void Main(string[] args)
        {
        }
 
        private List<EventHandler> subscribedEvents;
        private event EventHandler _OnEvent;
        public event EventHandler OnEvent
        {
            add
            {
                if (!this.subscribedEvents.Contains(value))
                {
                    this._OnEvent += value;
                    this.subscribedEvents.Add(value);
                }
            }
            remove
            {
                if (this.subscribedEvents.Contains(value))
                {
                    this._OnEvent -= value;
                    this.subscribedEvents.Remove(value);
                }
            }
        }
 
        private void onEventRaise()
        {
            if (OnEvent != null)
            {
                OnEvent(this, new EventArgs()); 
            }
        }
    }
}

Open in new window

0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 2000 total points
ID: 24277321
I'm actually not sure (and very curious) as to why that is. It could possibly be due to the way I implemented the OnEvent event.

However, that was not the intended use of OnEvent. The private event is the one you should be checking for null. The public event is more just for show. See the code posted below just to reassure that a private event will be fired/handled.
//////////////////////////////////////////////////
// Main
//////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Class1 c = new Class1();
 
            c.OnEvent += new EventHandler(c_OnEvent);
            c.AProperty = "test";
            c.AProperty = "test2";
 
            Console.ReadKey();
        }
 
        static void c_OnEvent(object sender, EventArgs e)
        {
            Console.WriteLine("Event raised!!");
        }
    }
}
 
//////////////////////////////////////////////////
// Class 1
//////////////////////////////////////////////////
using System.Collections.Generic;
 
using System;
 
namespace ConsoleApplication1
{
    class Class1
    {
        private string someData;
 
        private List<EventHandler> subscribedEvents;
        private event EventHandler _OnEvent;
        public event EventHandler OnEvent
        {
            add
            {
                if (!this.subscribedEvents.Contains(value))
                {
                    this._OnEvent += value;
                    this.subscribedEvents.Add(value);
                }
            }
            remove
            {
                if (this.subscribedEvents.Contains(value))
                {
                    this._OnEvent -= value;
                    this.subscribedEvents.Remove(value);
                }
            }
        }
 
        public Class1()
        {
            this.subscribedEvents = new List<EventHandler>();
        }
 
        public string AProperty
        {
            set
            {
                this.someData = value;
                onEventRaise();
            }
        }
 
        private void onEventRaise()
        {
            if (this._OnEvent != null)
            {
                this._OnEvent(this, new EventArgs());
            }
        }
    }
}

Open in new window

0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 24279398
I take it that gave you what you were looking for?
0
 

Author Comment

by:brettr
ID: 24279507
Yes, I'm also curious why the public event didn't work on null check.

Thanks.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question