C# event


Release date:2023-09-05 Update date:2023-10-13 Editor:admin View counts:346

Label:

C# event

An Event is basically a user action, such as keystrokes, clicks, mouse movements, etc., or prompts, such as system-generated notifications. The application needs to respond to the event when it occurs. For example, interrupt.

Event mechanism is used in C# to realize the communication between threads.

Using delegates through events

Events are declared and generated in a class and are associated with an event handler by using a delegate in the same class or another class. The class that contains events is used to publish events. This is called the publisher class. Other classes that accept this event are called subscriber classes. Events use the publish-subscribe model.

A publisher is an object that contains event and delegate definitions. The relationship between events and delegates is also defined in this object. Objects of the publisher class call this event and notify other objects.

A subscriber is an object that accepts events and provides event handlers. The delegate in the publisher class invokes the method (event handler) in the subscriber class.

Declare event

To declare an event within a class, you must first declare the delegate typeof the event. For example:

public delegate void BoilerLogHandler(string status);

Then, declare the event itself, using the event keywords:

// Define events based on the above delegation
public event BoilerLogHandler BoilerEventLog;

The above code defines a file named BoilerLogHandler and a commission named BoilerEventLog event that invokes the delegate when it is generated.

Example

Example 1

using System;
namespace SimpleEvent
{
  using System;
  /***********Publisher Class***********/
  public class EventTest
  {
    private int value;
    public delegate void NumManipulationHandler();
    public event NumManipulationHandler ChangeNum;
    protected virtual void OnNumChanged()
    {
      if ( ChangeNum != null )
      {
        ChangeNum(); /* Event triggered */
      }else {
        Console.WriteLine( "event not fire" );
        Console.ReadKey(); /* Enter to continue */
      }
    }
    public EventTest()
    {
      int n = 5;
      SetValue( n );
    }
    public void SetValue( int n )
    {
      if ( value != n )
      {
        value = n;
        OnNumChanged();
      }
    }
  }
  /***********Subscriber Class***********/
  public class subscribEvent
  {
    public void printf()
    {
      Console.WriteLine( "event fire" );
      Console.ReadKey(); /* Enter to continue */
    }
  }
  /***********trigger***********/
  public class MainClass
  {
    public static void Main()
    {
      EventTest e = new EventTest(); /* Instantiated object,
        no event triggered for the first time
*/
      subscribEvent v = new subscribEvent(); /* Instantiating objects */
      e.ChangeNum += new EventTest.NumManipulationHandler( v.printf );
/* register */
      e.SetValue( 7 );
      e.SetValue( 11 );
    }
  }
}

When the above code is compiled and executed, it produces the following results:

event not fire
event fire
event fire

This example provides a simple application for troubleshooting a hot water boiler system. When the maintenance engineer inspects the boiler, the temperature and pressure of the boiler are automatically recorded in the logfile with the notes of the maintenance engineer.

Example 2

using System;
using System.IO;
namespace BoilerEventAppl
{
   // boiler class
   class Boiler
   {
      private int temp;
      private int pressure;
      public Boiler(int t, int p)
      {
         temp = t;
         pressure = p;
      }
      public int getTemp()
      {
         return temp;
      }
      public int getPressure()
      {
         return pressure;
      }
   }
   // Event Publisher
   class DelegateBoilerEvent
   {
      public delegate void BoilerLogHandler(string status);
      // Define events based on the above delegation
      public event BoilerLogHandler BoilerEventLog;
      public void LogProcess()
      {
         string remarks = "O. K";
         Boiler b = new Boiler(100, 12);
         int t = b.getTemp();
         int p = b.getPressure();
         if(t > 150 \|\| t < 80 \|\| p < 12 \|\| p > 15)
         {
            remarks = "Need Maintenance";
         }
         OnBoilerEventLog("Logging Info:\\n");
         OnBoilerEventLog("Temparature " + t + "\\nPressure: " + p);
         OnBoilerEventLog("\\nMessage: " + remarks);
      }
      protected void OnBoilerEventLog(string message)
      {
         if (BoilerEventLog != null)
         {
            BoilerEventLog(message);
         }
      }
   }
   // This class retains the terms for writing to log files
   class BoilerInfoLogger
   {
      FileStream fs;
      StreamWriter sw;
      public BoilerInfoLogger(string filename)
      {
         fs = new FileStream(filename, FileMode.Append,
FileAccess.Write);
         sw = new StreamWriter(fs);
      }
      public void Logger(string info)
      {
         sw.WriteLine(info);
      }
      public void Close()
      {
         sw.Close();
         fs.Close();
      }
   }
   // event subscriber
   public class RecordBoilerInfo
   {
      static void Logger(string info)
      {
         Console.WriteLine(info);
      }//end of Logger
      static void Main(string[] args)
      {
         BoilerInfoLogger filelog = new
BoilerInfoLogger("e:\\\\boiler.txt");
         DelegateBoilerEvent boilerEvent = new DelegateBoilerEvent();
         boilerEvent.BoilerEventLog += new
         DelegateBoilerEvent.BoilerLogHandler(Logger);
         boilerEvent.BoilerEventLog += new
         DelegateBoilerEvent.BoilerLogHandler(filelog.Logger);
         boilerEvent.LogProcess();
         Console.ReadLine();
         filelog.Close();
      }//end of main
   }//end of RecordBoilerInfo
}

When the above code is compiled and executed, it produces the following results:

Logging info:

Temperature 100
Pressure 12

Message: O. K

Powered by TorCMS (https://github.com/bukun/TorCMS).