Solved

c# event handling

Posted on 2011-02-23
13
316 Views
Last Modified: 2013-12-17
Hi,

I inherit this class:

class test
{
  public enum NotificationMessages  
    {
        Aborted,
        WaitingToConnect,
        Connected,
}
       public delegate void NotificationMessageDelegate(object sender, NotificationMessages);
       private event NotificationMessageDelegate m_NotificationMessage;
 
       public event NotificationMessageDelegate NotificationMessage
        {
            add { m_NotificationMessage += new NotificationMessageDelegate(value); }
            remove { m_NotificationMessage -= new NotificationMessageDelegate(value); }
        }


      private void SendNotifiation(NotificationMessages m)
        {
            if (m_NotificationMessage != null)
            {
                // send notification message out
                m_NotificationMessage(this, m);
            } // if
        }
      public processSerialPort()
     {
          ...
           SendNotifiation(NotificationMessages.DownloadFlashStart);
          ...
      }

}

Now in the client of test, how can I get this message?

{
...
Test t  = new Test();

          t.NotificationMessage += new Class1.NotificationMessageDelegate(c1_NotificationMessage);     // i register event handler

       //??? how can subscribe event
..
}

    void c1_NotificationMessage(object sender, Class1.NotificationMessages m)
        {
            //????
        }
 

Thanks,
JT
0
Comment
Question by:jtran007
  • 9
  • 3
13 Comments
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
if i understand your layout, this should do it..(using invoke)

private void SendNotifiation(NotificationMessages m)
        {
            if (m_NotificationMessage != null)
            {
                // send notification message out
                m_NotificationMessage.Invoke(this, m);
            } // if
        }
0
 
LVL 6

Accepted Solution

by:
ViceroyFizzlebottom earned 500 total points
Comment Utility
So, I rewrote your code a little to conform to Microsoft's "best practices" as far as defining and using events. The code below can be copy/pasted into a simple console application and ran, achieving what you need. I'm using EventHandler<T> instead of defining a separate delegate, but it achieves the same thing.

Here is the MSDN documentation on events, refer to the 'Related Sections' portion for links on publishing events, and the link on subscribing to events. The code sample below uses those guidelines.

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

namespace SampleEvents
{
    class Program
    {
        static void Main(string[] args)
        {
            var t = new Test();
            t.NotificationMessage += t_NotificationMessage;

            // This method will raise event that will be handled in t_NotificationMessage
            t.ProcessSerialPort();

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }

        static void t_NotificationMessage(object sender, NotificationMessages e)
        {
            Console.WriteLine("Current status is: " + e.CurrentStatus);
        }
    }

    public class NotificationMessages : EventArgs
    {
        [Flags]
        public enum Message
        {
            Aborted,
            WaitingToConnect,
            Connected
        }

        public Message CurrentStatus { get; set; }
    }

    public class Test
    {

        public event EventHandler<NotificationMessages> NotificationMessage;

        private void OnSendNotification(NotificationMessages messages)
        {
            if (NotificationMessage != null)
            {
                NotificationMessage(this, messages);
            }
        }

        public void ProcessSerialPort()
        {
            // Do stuff

            // Fire event
            OnSendNotification(new NotificationMessages()
                                   {
                                       CurrentStatus = NotificationMessages.Message.WaitingToConnect
                                   });
        }
    }
}

Open in new window

0
 
LVL 6

Expert Comment

by:ViceroyFizzlebottom
Comment Utility
Uh, forgot to link the MSDN article above:

http://msdn.microsoft.com/en-us/library/awbftdfh.aspx
0
 

Author Comment

by:jtran007
Comment Utility
Hi p_davis,

Thanks for your suggestion.

Once I register event like:

Test t  = new Test();

          t.NotificationMessage += new Class1.NotificationMessageDelegate(c1_NotificationMessage);

how do i subscribe it, so that the function c1_NofiticationMessage can be called?

Thanks,
JT
0
 

Author Comment

by:jtran007
Comment Utility
Hi,

Thanks for your assistance. The thing is that during process data coming from serial port,
the class Test use SendNotification(...) as listed above notifies client by its message. I'd like to capture message sent by SendNotification. How my client do it?

Thanks,
JT
0
 

Author Comment

by:jtran007
Comment Utility
Hi,

I mean how do I raise event from client to receive message from SendNotification. Since the
object Test() use many SendNotification during the course of processing serial port.

Thanks,
JT
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:jtran007
Comment Utility
Hi vicery,

What does it mean ^Flags in your codeÉ

Thanks,
JT
0
 

Author Comment

by:jtran007
Comment Utility
Hi vicery,

How do I remove message once it was launchedÉ Is it necessary to remove the messageÉ

Thanks,
JT
0
 
LVL 6

Expert Comment

by:ViceroyFizzlebottom
Comment Utility
jtran007,

The [Flags] is simply an attribute indicating that the enum can be used as a bit field (basically it allows more than one value to be selected). Actually, it's just force of habit for me and you don't have to have it there. You could safely remove it if you wanted. Here's the MSDN for the FlagsAttribute: http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx

Also, events are based on a publisher/subscriber model in that the class which publishes the event knows nothing about any consumers. Therefore, you can't raise the event from a client (subscriber), you can only respond to the event once it's been raised. If you wanted to take action on the Test class instance from your client, you would need to expose a method or property from your Test class which the client could call of check to determine the current status like:

public void ClientMethod()
{
    Test t = new Test();
    // Do some stuff
    NotificationMessage m = t.GetCurrentStatus();
}

In the case above, there would be no need to even have the event(s) in your Test class.

Finally, I'm not sure I understand what you mean by removing the message. Can you elaborate on that?
0
 

Author Comment

by:jtran007
Comment Utility
Hi,
 How do I use MethodInvoker to call event since I enherited a class with big codes handling
seriort?
Thanks,
JT
0
 

Author Comment

by:jtran007
Comment Utility
Hi,
I try this:

                t.NotificationMessage += new NotificationMessageDelegate(t_NotificationMessage);
...
     void Adt42To45_NotificationMessage(object sender, NotificationMessages m)
        {
              if (textBox1.InvokeRequired)
            {
                textBox1.BeginInvoke(new MethodInvoker(delegate() { t_NotificationMessage(sender, m); }));

            }
              textBox1.Text = m.ToString();
              textBox1.Refresh();
              textBox1.Update();

        }

But it is not working. Could you help?
Thanks,
JT
0
 

Author Comment

by:jtran007
Comment Utility
Hi
sorry
  void t_NotificationMessage(object sender, NotificationMessages m)
 instead of

  void Adt42To45_NotificationMessage(object sender, NotificationMessages m)
 JT
0
 

Author Closing Comment

by:jtran007
Comment Utility
Thanks,'
JT
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

743 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now