📘 C# Blog Series – Blog 21 **“C# Threading — एक साथ Multiple काम कैसे कराते हैं?

📘 C# Blog Series – Blog 21

**“C# Threading — एक साथ Multiple काम कैसे कराते हैं?





(Real-Life Example: GPS Server में Multi-Device Parallel Handling)”**

जब आप ऐसा system बनाते हो जिसमें एक ही time पर हजारों operations होने हों —
जैसे आपका GPS Server जहाँ:

  • 1000 devices एक साथ packets भेजते हैं

  • हर device का अलग TCP connection

  • हर device का data अलग process

  • हर 10–30 सेकंड में नया packet

इस स्थिति में Single-thread code तुरंत slow हो जाता है।

Multi-threading C# में वो feature है जिससे आपका system एक साथ कई काम कर सकता है।


🟦 1. Thread क्या है? (Super Simple Explanation)

Thread = एक छोटा worker
जोCPU पर एक समय में एक task करता है।

Real Life Example

Restaurant में:

  • एक waiter → single-thread

  • 10 waiters → multi-thread

जब काम ज्यादा हो → single-thread system धीमा पड़ जाता है।


🟢 2. C# में Thread कैसे बनता है?

Basic Example:

new Thread(() => { Console.WriteLine("Thread Running"); }).Start();

यह code main thread के साथ parallel चलेगा।


🌟 3. Real-Life Example: GPS Server में हर Device एक Thread पर

आपके TCP server में हर device एक separate thread पर चलता है:

void StartServer() { while (true) { var client = listener.AcceptTcpClient(); Thread t = new Thread(() => HandleClient(client)); t.Start(); } }

हर new client → new thread → new parallel work
Server कभी block नहीं होता।


4. HandleClient — हर device parallel चलता है

void HandleClient(TcpClient client) { // इस thread पर GPS packets process होंगे while (true) { byte[] buffer = new byte[1024]; int read = client.GetStream().Read(buffer, 0, buffer.Length); // device की processing बाकी devices के साथ parallel चलती है } }

यही कारण है कि आपके server पर 2000 devices भी parallel handle हो पाते हैं।


🟠 5. Thread.Sleep() — Thread को कुछ समय रोकना

Thread.Sleep(1000); // 1 second

Real GPS example:
अगर packet incomplete आया →
कुछ ms wait करके next bytes read कर सकते हैं।


🔵 6. Background Threads (Server tasks के लिए best)

Background thread खुद बंद हो जाता है जब main बंद हो।

Thread t = new Thread(Work); t.IsBackground = true; t.Start();

Real-life use:

  • Auto cleanup

  • Memory optimize

  • Heartbeat check

  • Offline devices remove


🟣 7. Thread Pool — Best for High Traffic Server

Thread pool pre-created threads use करता है →
नई thread बनाने का overhead नहीं।

ThreadPool.QueueUserWorkItem(x => { ProcessPacket(packet); });

GPS server में यह performance बढ़ाता है।


🚀 8. TASKS (Thread का Modern Version)

C# में thread का modern version है Task.

Task.Run(() => { ProcessPacket(packet); });

Task multi-threading को बहुत आसान और safe बना देता है।


🧠 9. Real-Life GPS Example: Every Packet Parallel Process

Task.Run(() => ProcessPacket(packet));

अब 100 packets एक साथ भी आएँ →
Server fast रहेगा।


10. Parallel.For / Parallel.ForEach — Super Fast Loops

अगर आपको एक बड़ी list पर fast loop चाहिए:

Parallel.ForEach(devices, device => { ProcessDevice(device); });

यह normal loop से 3×–10× तेज़ चलता है।


🔥 11. Real GPS Example: 2000 Devices पर Health Check

Parallel.ForEach(ConnectedDevices, d => { if ((DateTime.Now - d.LastUpdated).TotalSeconds > 60) d.Status = "Offline"; });

Ultra fast health system!


🛑 12. Thread Safety — सबसे Important Warning

जब multiple threads एक ही variable को modify करते हैं,
तो problem हो सकती है → race condition।

Example:

count++; // Dangerous in multi-thread

Safe version:

Use lock:

lock (locker) { count++; }

GPS server में shared lists, dictionary modify करते समय lock जरूरी है।


🔐 13. Real-Life Example: ConnectedDevices Dictionary safe update

lock(deviceLock) { Devices[device.IMEI] = device; }

Thread safety = stable server.


🔚 Conclusion

C# Multi-threading gives:

✔ Real-time parallel processing
✔ Smooth GPS device handling
✔ High-performance TCP server
✔ Non-blocking architecture
✔ Faster API responses
✔ Background work execution

Threading बिना कोई भी high-traffic system चल ही नहीं सकता।

आपने आज production-level backend development का एक और powerful concept सीख लिया।

Post a Comment

0 Comments

Translate

Close Menu