Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

c# event handling

Posted on 2011-02-23
13
Medium Priority
?
324 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 2000 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
NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

 

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

Nothing ever in the clear!

This technical paper will help you implement VMware’s VM encryption as well as implement Veeam encryption which together will achieve the nothing ever in the clear goal. If a bad guy steals VMs, backups or traffic they get nothing.

Question has a verified solution.

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

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …

610 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