C# Event
Event Basically it is a user operation, such as key press, click, mouse movement, etc., or some occurrence, such as system Generated notification. Applications need to respond to events when they occur. For example, interrupts. Events are used for inter-process communication.
Using delegates through events
Events are declared and generated in a class, and are associated with event handlers by using delegates in the same class or other classes. The class containing the event is used to publish the event. This is called the publisher class. Other classes that accept this event are called subscriber classes. Events use the publisher-subscriber model.
Publisher (publisher) is an object containing event and delegate definitions. The connection between events and delegates is also defined in this object. Objects of the publisher class call this event and notify other objects.
Subscriber (subscriber) is an object that accepts events and provides event handlers. The delegate in the publisher class calls methods (event handlers) in the subscriber class.
Declare events (Event)
When declaring an event inside a class, you must first declare the delegate type of the event. For example:
public delegate void BoilerLogHandler(string status);
Then, declare the event itself, using the event keyword:
// 基于上面的委托定义事件 public event BoilerLogHandler BoilerEventLog;
The above code defines a delegate named BoilerLogHandler and an event named BoilerEventLog, which calls the delegate when generated.
Example 1
using System; namespace SimpleEvent { using System; public class EventTest { private int value; public delegate void NumManipulationHandler(); public event NumManipulationHandler ChangeNum; protected virtual void OnNumChanged() { if (ChangeNum != null) { ChangeNum(); } else { Console.WriteLine("Event fired!"); } } public EventTest(int n ) { SetValue(n); } public void SetValue(int n) { if (value != n) { value = n; OnNumChanged(); } } } public class MainClass { public static void Main() { EventTest e = new EventTest(5); e.SetValue(7); e.SetValue(11); Console.ReadKey(); } } }
When the above code is compiled and executed, it will produce the following results:
Event Fired! Event Fired! Event Fired!
Example 2
This example provides a Simple app for hot water boiler system troubleshooting. When the maintenance engineer inspects the boiler, the temperature and pressure of the boiler are automatically recorded into the log file along with the maintenance engineer's notes.
using System; using System.IO; namespace BoilerEventAppl { // boiler 类 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; } } // 事件发布器 class DelegateBoilerEvent { public delegate void BoilerLogHandler(string status); // 基于上面的委托定义事件 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); } } } // 该类保留写入日志文件的条款 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(); } } // 事件订阅器 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