In C#, events are a key part of the language's event-driven programming model. An event allows a class or object to notify other classes or objects when something of interest occurs. This capability is typically used for user interface actions, such as button clicks or mouse movements, but can be applied in various scenarios.
To define an event in C#, you typically follow these steps:
Here's an example demonstrating how to handle events:
// Delegate declaration
public delegate void Notify();
// Class that publishes the event
public class Publisher
{
public event Notify ProcessCompleted;
public void StartProcess()
{
// Process code here...
// Raise the event
ProcessCompleted?.Invoke();
}
}
// Subscriber class
public class Subscriber
{
public void Subscribe(Publisher publisher)
{
publisher.ProcessCompleted += OnProcessCompleted;
}
private void OnProcessCompleted()
{
Console.WriteLine("Process completed!");
}
}
// Example usage
class Program
{
static void Main(string[] args)
{
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber();
subscriber.Subscribe(publisher);
publisher.StartProcess(); // This will trigger the event
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?