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

Task क्या है

एक Task एक वादा है कि कुछ काम बाद में खत्म होगा, जैसे एक pager जो आपकी table तैयार होने पर buzz करता है। यह background में चल रहे एक ऐसे job को represent करता है जो कोई result नहीं देता।

In this page:

  1. Task
Syntax
csharp
static async Task MethodNameAsync()
{
    await Task.Delay(milliseconds);
}

Task task = MethodNameAsync();
await task;

Task

Task एक asynchronous operation को represent करता है जो कोई value produce नहीं करता, बिल्कुल वैसे जैसे void methods synchronously कुछ return नहीं करते।

आप किसी Task को await करके जान सकते हैं कि यह कब खत्म होता है, या CPU-bound काम को background thread पर offload करने के लिए Task.Run उपयोग कर सकते हैं। Tasks को Task.WhenAll और Task.WhenAny से compose किया जा सकता है।

Note:
  • Task.Run(() => ...) CPU-bound काम के लिए है
  • aकेला await स्वाभाविक रूप से asynchronous I/O के लिए काफी है।

उदाहरण: Task

markup
using System;
using System.Threading.Tasks;

class Program
{
    static async Task DoWorkAsync()
    {
        await Task.Delay(50);
        Console.WriteLine("Work done");
    }

    static async Task Main(string[] args)
    {
        Task t1 = DoWorkAsync();
        Task t2 = DoWorkAsync();

        await Task.WhenAll(t1, t2);
        Console.WriteLine("Both tasks finished");
    }
}
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. किसी Task को await करना भूल जाना, जिससे exceptions खो जाते हैं और काम खत्म नहीं होता।
  2. Async APIs मौजूद होने पर I/O काम के लिए Task.Run उपयोग करना।
  3. async code में await Task.Delay के बजाय Thread.Sleep उपयोग करना।
🔒

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.