C# में Events वो फीचर है जो आपके application में
real-time reaction लाता है।
GPS server में events का सबसे important role है:
Device connected
Device disconnected
Packet received
Low battery alert
SOS signal
Overspeed alert
जैसे ही कोई घटना होती है → आपका system खुद “react” कर सकता है।
आज हम C# events को सबसे आसान तरीके + आपके GPS server example से समझेंगे।
Event =
जब कुछ होता है → उसे सुनकर action लेना
Real-life example:
Doorbell बजते ही आप दरवाज़ा खोलते हैं
मोबाइल में notification आते ही आप देखते हैं
कार में seatbelt alert आते ही driver belt लगाता है
Programming में यही होता है →
System event trigger करता है, subscriber उसका response देता है।
Event बनाने के लिए दो चीज़ चाहिए:
Delegate (method signature define करता है)
Event (घटना घोषित करता है)
public delegate void MyHandler(string message);
public class Test
{
public event MyHandler OnMessage;
}
OnMessage?.Invoke("Hello Event!");
यह कहता है → “सब listeners को notify करो!”
test.OnMessage += (msg) => Console.WriteLine(msg);
जिस function को subscribe किया है → वो event आते ही run होगा।
आपका TCP GPS server कई events produce करता है:
अब हम इन्हें C# events से model करते हैं।
public delegate void DeviceEventHandler(GPSDevice device);
public class GPSManager
{
public event DeviceEventHandler DeviceConnected;
public event DeviceEventHandler DeviceDisconnected;
}
public void AddDevice(GPSDevice device)
{
connectedDevices.Add(device);
DeviceConnected?.Invoke(device);
}
gpsManager.DeviceConnected += (device) =>
{
Console.WriteLine("Connected: " + device.IMEI);
};
जैसे ही कोई device connect → यह code अपने आप चलेगा।
gpsManager.DeviceConnected += (d) =>
{
Log("Device online: " + d.IMEI);
NotifyWebSocketClients(d);
};
gpsManager.DeviceDisconnected += (d) =>
{
Log("Device disconnected: " + d.IMEI);
};
d.OnLowBattery += (device) =>
{
SendSMS(device.Owner, "Low Battery Alert!");
};
GPS device SOS send करता है:
SOS,IMEI=861128068064267
Event trigger:
public event DeviceEventHandler OnSOS;
Device processing:
OnSOS?.Invoke(this);
Listener:
device.OnSOS += d => AlertPolice(d);
Server instantly react करेगा।
यही है events की ताकत।
Bill printed
Item added
Low inventory alert
Student login event
Attendance marked event
Order placed
Payment success
Shipment dispatched
Player died
Level completed
Coin collected
Events everywhere!
Events आपके सिस्टम में “real-time reaction power” जोड़ते हैं:
✔ Instant actions
✔ Loose coupling
✔ Clean architecture
✔ Easy extend
✔ Real-time systems के लिए perfect
GPS server, banking, signaling systems—
सभी events पर heavily depend करते हैं।
0 Comments
Thanks for Commenting on our blogs, we will revert back with answer of your query.
EmojiThanks & Regards
Sonu Yadav