Solved

c# event handling

Posted on 2011-02-23
13
318 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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

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
 

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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Video Player 11 23
EF5: Question about Metadata Artifact Processing 4 15
How to call weather service by using asmx? 4 29
Help with exporting to excel 4 26
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

786 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