Event (Event) in C #

Events (Events) are the actions of users, such as pressing keys, clicking, moving mouse . Applications need to respond to these events when they appear. For example, interrupts. Events (Events) are used to communicate within the process.

Use Delegate with Event in C #

Events are declared and created in a class and linked to Event Handler by using Delegates within the same class or some other class. The class that contains the Event is used to publish the event. This is called the Publisher class. Some other classes that accept this Event are called Subscriber class. Events in C # use the Publisher-Subscriber model .

A Publisher in C # is an object that contains the definition of that event and delegate. Event-delegate relationships are also defined in this object. A Publisher class object summons the Event and it is notified to other objects.

A Subscriber in C # is an object that accepts the event and provides an Event Handler. Delegate in the Event Handler (Event Handler) class of the Subscriber class.

Declaring Event in C #

To declare an Event inside a class, first a delegate type for that Event must be declared. For example:

 public delegate void BoilerLogHandler ( string status ); 

Next, the Event itself is declared, using the event keyword in C #:

 //định nghĩa event dựa vào delegate ở trên public event BoilerLogHandler BoilerEventLog ; 

The above code defines a delegate with the name BoilerLogHandler and an Event named BoilerEventLog , which summons that delegate when it is created.

 using System ; namespace SampleApp { public delegate string MyDel ( string str ); class EventProgram { event MyDel MyEvent ; public EventProgram () { this . MyEvent += new MyDel ( this . WelcomeUser ); } public string WelcomeUser ( string username ) { return "TipsMake.com xin chào " + username ; } static void Main ( string [] args ) { EventProgram obj1 = new EventProgram (); string result = obj1 . MyEvent ( "bạn" ); Console . WriteLine ( result ); } } } 

Compiling and running the above C # program will produce the following results:

 Welcome to TipsMake.com 

Example 2

This example provides a simple application to troubleshoot a pot system over hot water. When the boiler maintenance engineer, boiler temperature and pressure are automatically recorded in a log file along with the notes of this maintenance engineer.

The program will be as follows:

 using System ;
using System . IO ; namespace QTMCsharp { 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 ); //định nghĩa sự kiện dựa vào delegate trên public event BoilerLogHandler BoilerEventLog ; public void LogProcess () { string remarks = "OK!" ; Boiler b = new Boiler ( 100 , 12 ); int t = b . getTemp (); int p = b . getPressure (); if ( t > 150 || t < 80 || p < 12 || p > 15 ) { remarks = "Cần duy trì" ; } OnBoilerEventLog ( "Thông tin bản ghi:n" ); OnBoilerEventLog ( "Nhiệt độ: " + t + "nÁp suất: " + p ); OnBoilerEventLog ( "nThông báo: " + 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 (); } } class TestCsharp { static void Logger ( string info ) { Console . WriteLine ( info ); } static void Main ( string [] args ) { Console . WriteLine ( "Ví dụ minh họa sự kiện trong C#" ); Console . WriteLine ( "-------------------------------" ); 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 (); Console . ReadKey (); filelog . Close (); } } }

And when you run this program you will get results:

 Example illustrating events in C # 
-------------------------------
Record information:

Temperature: 100
Pressure: 12

Notice: OK!

According to Tutorialspoint

Previous article: Delegate in C #

Next article: Collection in C #

5 ★ | 1 Vote

May be interested

  • How to Schedule an Event in OutlookHow to Schedule an Event in Outlook
    microsoft outlook now has the option to schedule right in the interface without having to use another application. after you schedule a meeting or any calendar in outlook, the application will send a notification when the schedule is close, or according to the user's settings.
  • Fix Event ID 454 error on Windows 10Fix Event ID 454 error on Windows 10
    in this article, tipsmake.com will identify potential cause (s) for event id 454 errors in user profiles, leading to performance issues, as well as provide an appropriate solution to fix the error. .
  • Apple Announces New iOS, iPadOS, WatchOS, and macOS Launch DatesApple Announces New iOS, iPadOS, WatchOS, and macOS Launch Dates
    apple has just announced the schedule for the wwdc 2022 event. accordingly, wwdc 2022 will be held online from june 6 to 10. developers, technology enthusiasts, and consumers alike who are interested in upcoming updates and new features on apple's operating systems should rate it.
  • Event Loop in Node.jsEvent Loop in Node.js
    node.js is a single thread application, but it supports concurrent processing through event definitions and callbacks. as all node.js apis are asynchronous and single threaded, it uses the async function to maintain concurrency. node.js uses the pattern observer.
  • Instructions for registering for the invitation to attend the Bphone launch event 2Instructions for registering for the invitation to attend the Bphone launch event 2
    you are a technology enthusiast, love new products, you should not miss the event of launching bphone 2.
  • IFA 2019: What to expect at Europe's biggest tech event?IFA 2019: What to expect at Europe's biggest tech event?
    this year's event will still take place in berlin, germany, from september 6 to 11.
  • Manage the Event Log with the command lineManage the Event Log with the command line
    for many of us, using the command line - command line to control and use some of the functions in the windows system will cause them to have headaches and problems. however, if you have to set up an automatic function system in windows and other server operating systems, the command line is an irreplaceable tool ...
  • How to try out the coolest features from Google's event right nowHow to try out the coolest features from Google's event right now
    google's biggest event of the year, google i/o, has come and gone. and there were a number of new features announced at the conference that you can try out right now. here are some of the most exciting.
  • Genshin Impact: How to unlock endings in Ningguang's companion eventGenshin Impact: How to unlock endings in Ningguang's companion event
    hangout event – ​​a companion event, is a special story quest for most of the 4 star characters in genshin impact. this event is basically allowing you to spend time with your favorite individual characters.
  • What's special about Apple's 'Let Loose' event?What's special about Apple's 'Let Loose' event?
    apple has announced its first special event of 2024, let loose. unlike the annual software-focused wwdc event it announced for march 2024, this event appears to be all about the ipad.