Solved

c# event handling

Posted on 2011-02-23
13
317 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
ID: 34967066
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
ID: 34967885
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
ID: 34967888
Uh, forgot to link the MSDN article above:

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

Author Comment

by:jtran007
ID: 34969005
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
ID: 34969039
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
ID: 34969056
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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

Author Comment

by:jtran007
ID: 34969182
Hi vicery,

What does it mean ^Flags in your codeÉ

Thanks,
JT
0
 

Author Comment

by:jtran007
ID: 34969206
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
ID: 34971544
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
ID: 34971704
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
ID: 34971950
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
ID: 34971967
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
ID: 35380733
Thanks,'
JT
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
detecting  the added row index in a datagridview 3 61
DataGridView Events ? 3 37
Export import database 4 43
Best resource to learn entity framework 2 8
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
Both in life and business – not all partnerships are created equal. As the demand for cloud services increases, so do the number of self-proclaimed cloud partners. Asking the right questions up front in the partnership, will enable both parties …

896 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

20 Experts available now in Live!

Get 1:1 Help Now