C# Event
A C# Event is a member used to send specific event notifications to subscribers. Events are typically used to implement the observer pattern, which allows an object to notify other objects of changes in its state without knowing the details of those objects.
Event Basically, it is a user action, such as a key press, click, mouse movement, etc., or some notification information, such as a system-generated notification. An application needs to respond to events when they occur. For example, an interrupt.
In C#, the event mechanism is used to implement communication between threads.
Key points:
- Declare a Delegate: defines the delegate type that the event will use. A delegate is a function signature.
- Declare an Event: When using
eventkeyword to declare an event. - Trigger events: invoke the event at the appropriate time to notify all subscribers.
- Subscribe to and Unsubscribe from Events: other classes can, through the
+=and-=operator, subscribe to and unsubscribe from events.
Using Delegates Through Events
An event is declared and generated in a class, and is associated with an event handler through a delegate in the same class or in another class. The class containing the event publishes the event. This is called the publisher class. Other classes that accept the event are called subscriber class. Events use the publish-subscribe (publisher-subscriber) model.
publisher is an object that contains the event and delegate definitions. The association between the event and the delegate is also defined in this object. An object of the publisher class invokes the event and notifies other objects.
subscriber is an object that accepts the event and provides an event handler. The delegate in the publisher class calls a method (event handler) in the subscriber class.
Declaring an Event
To declare 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:
// Define event based on the above delegate
public event BoilerLogHandler BoilerEventLog;
The above code defines a delegate named BoilerLogHandler and an event named BoilerEventLog that calls the delegate when it is raised.
The following example shows how to use events in C#:
Example
using
System
;
namespace
EventDemo
{
// Define a delegate type for the event handler
public
delegate
void
NotifyEventHandler
(
object
sender, EventArgs e
)
;
// Publisher class
public
class
ProcessBusinessLogic
{
// Declare the event
public
event
NotifyEventHandler ProcessCompleted
;
// Method that raises the event
protected
virtual
void
OnProcessCompleted
(
EventArgs e
)
{
ProcessCompleted
?.
Invoke
(
this
, e
)
;
}
// Simulate the business logic process and raise the event
public
void
StartProcess
(
)
{
Console
.
WriteLine
(
"Process Started!"
)
;
// Actual business logic can be added here
// Business logic complete, raise the event
OnProcessCompleted
(
EventArgs
.
Empty
)
;
}
}
// Subscriber class
public
class
EventSubscriber
{
public
void
Subscribe
(
ProcessBusinessLogic process
)
{
process
.
ProcessCompleted
+=
Process_ProcessCompleted
;
}
private
void
Process_ProcessCompleted
(
object
sender, EventArgs e
)
{
Console
.
WriteLine
(
"Process Completed!"
)
;
}
}
class
Program
{
static
void
Main
(
string
[
]
args
)
{
ProcessBusinessLogic process
=
new
ProcessBusinessLogic
(
)
;
EventSubscriber subscriber
=
new
EventSubscriber
(
)
;
// Subscribe to the event
subscriber
.
Subscribe
(
process
)
;
// Start the process
process
.
StartProcess
(
)
;
Console
.
ReadLine
(
)
;
}
}
}
Description
1. Define the delegate type:
public delegate void NotifyEventHandler(object sender, EventArgs e);
This is a delegate type that defines the signature of the event handler. It is common to use EventHandler or EventHandler instead of a custom delegate.
2. Declare the event:
public event NotifyEventHandler ProcessCompleted;
This is an event using the NotifyEventHandler delegate type.
3. Raise the event:
protected virtual void OnProcessCompleted(EventArgs e)
{
ProcessCompleted?.Invoke(this, e);
}
This is a protected method used to raise the event. Use the ?.Invoke syntax to ensure the event is invoked only when there are subscribers.
4. Subscribe to and unsubscribe from events:
process.ProcessCompleted += Process_ProcessCompleted;
Subscribers use the += operator to subscribe to the event and define the event handler Process_ProcessCompleted。
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
(
)
;
/* Press 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
(
)
;
/* Press Enter to continue */
}
}
/Triggers/
public
class
MainClass
{
public
static
void
Main
(
)
{
EventTest e
=
new
EventTest
(
)
;
/* Instantiate the object; no event is triggered the first time */
subscribEvent v
=
new
subscribEvent
(
)
;
/* Instantiate the object */
e
.
ChangeNum
+=
new
EventTest
.
NumManipulationHandler
(
v
.
printf
)
;
/* Register */
e
.
SetValue
(
7
)
;
e
.
SetValue
(
11
)
;
}
}
}
When the code above is compiled and executed, it produces the following result:
event not fire
event fire
event fire
This example provides a simple application for troubleshooting a hot-water boiler system. When a maintenance engineer inspects the boiler, the boiler's temperature and pressure are automatically recorded to a log file together with the engineer's remarks.
Example 2
using
System
;
using
System.IO
;
namespace
BoilerEventAppl
{
// Boiler class
class
Boiler
{
public
int
Temp
{
get
;
private
set
;
}
public
int
Pressure
{
get
;
private
set
;
}
public
Boiler
(
int
temp,
int
pressure
)
{
Temp
=
temp
;
Pressure
=
pressure
;
}
}
// Event publisher
class
DelegateBoilerEvent
{
public
delegate
void
BoilerLogHandler
(
string
status
)
;
// Define the event based on the above delegate
public
event
BoilerLogHandler BoilerEventLog
;
public
void
LogProcess
(
)
{
string
remarks
=
"O.K."
;
Boiler boiler
=
new
Boiler
(
100
,
12
)
;
int
temp
=
boiler
.
Temp
;
int
pressure
=
boiler
.
Pressure
;
if
(
temp
150
||
temp
<
80
||
pressure
<
12
||
pressure
15
)
{
remarks
="Need Maintenance"
;
}
OnBoilerEventLog
(
$
"Logging Info:\nTemperature: {temp}\nPressure: {pressure}\nMessage: {remarks}"
)
;
}
protected
void
OnBoilerEventLog
(
string
message
)
{
BoilerEventLog
?.
Invoke
(
message
)
;
}
}
// This class retains the provisions for writing to the log file
class
BoilerInfoLogger
:
IDisposable
{
private
readonly
StreamWriter _streamWriter
;
public
BoilerInfoLogger
(
string
filename
)
{
_streamWriter
=
new
StreamWriter
(
new
FileStream
(
filename, FileMode
.
Append
, FileAccess
.
Write
)
)
;
}
public
void
Logger
(
string
info
)
{
_streamWriter
.
WriteLine
(
info
)
;
}
public
void
Dispose
(
)
{
_streamWriter
?.
Close
(
)
;
}
}
// Event subscriber
public
class
RecordBoilerInfo
{
static
void
Logger
(
string
info
)
{
Console
.
WriteLine
(
info
)
;
}
static
void
Main
(
string
[
]
args
)
{
using
(
BoilerInfoLogger fileLogger
=
new
BoilerInfoLogger
(
"e:\boiler.txt"
)
)
{
DelegateBoilerEvent boilerEvent
=
new
DelegateBoilerEvent
(
)
;
boilerEvent
.
BoilerEventLog
+=
Logger
;
boilerEvent
.
BoilerEventLog
+=
fileLogger
.
Logger
;
boilerEvent
.
LogProcess
(
)
;
}
Console
.
ReadLine
(
)
;
}
}
}
When the code above is compiled and executed, it produces the following result:
Logging info:
Temperature 100
Pressure 12
Message: O. K