← Back to C# Course | Chapter 13: Async Programming | Lesson 6 of 6

Parallel.For क्या है

Parallel.For किसी loop के turns को एक साथ कई workers में बांट देता है, जैसे दोस्तों का एक group जिसमें हर एक अलग कमरा साफ़ करता है। यह बड़े jobs को तेज़ी से खत्म कर सकता है।

In this page:

  1. Parallel.For
Syntax
csharp
Parallel.For(start, endExclusive, i =>
{
    // body runs concurrently for each i
});

Parallel.For

Parallel.For loop iterations को कई threads में concurrently चलाता है, CPU-bound काम के लिए उपयोगी जहां iterations एक-दूसरे पर निर्भर नहीं करते।

यह data-parallel tasks के लिए manually threads manage करने का एक सरल विकल्प है। चूंकि iterations क्रम से बाहर और concurrently चलते हैं, shared mutable state को सुरक्षित या टाला जाना चाहिए।

Warning: Parallel.For के अंदर बिना synchronization के किसी shared variable को सीधे increment न करें — यह race conditions का कारण बनता है।

उदाहरण: Parallel.For

markup
using System;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        int total = 0;

        Parallel.For(1, 6, i =>
        {
            Interlocked.Add(ref total, i);
        });

        Console.WriteLine($"Total: {total}");
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Parallel.For के अंदर total += i से किसी shared variable को update करना, जो एक race condition है; Interlocked.Add या एक lock का उपयोग करें।
  2. यह मान लेना कि iterations order में चलते हैं, जबकि वे कई threads पर चलते हैं इसलिए printed lines जैसे results किसी भी order में आते हैं।
  3. यह उम्मीद करना कि end value शामिल होगी, जबकि Parallel.For(1, 6, ...) 1 से 5 तक चलता है क्योंकि upper bound exclusive है।
चैप्टर सारांश
  • async और await code को बिना block किए काम का इंतज़ार करने देते हैं।
  • Task और Task<T> asynchronous operations को represent करते हैं।
  • ConfigureAwait, CancellationToken, और Parallel.For asynchronous और parallel काम को control और cancel करते हैं।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.