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

async / await की Basics

async और await किसी program को कोई धीमा काम, जैसे download का इंतज़ार, शुरू करने और इंतज़ार के दौरान बाकी काम करने देते हैं। यह bread को toaster में डालकर juice डालने जैसा है बजाय बस घूरते रहने के।

In this page:

  1. async / await Basics
Syntax
csharp
static async Task<ReturnType> MethodNameAsync()
{
    await SomeAsyncOperation();   // pauses without blocking the thread
    return value;
}

ReturnType result = await MethodNameAsync();

async / await Basics

async किसी method को asynchronous चिह्नित करता है, इसे calling thread को block किए बिना किसी धीमे operation पर await से execution रोकने देते हुए।

Control caller को वापस चला जाता है जबकि awaited operation चलता है, फिर इसके पूरा होने पर method फिर से शुरू होता है। यह network या file access जैसे I/O-bound काम के दौरान applications को responsive रखता है।

Note: एक async method को Task या Task<T> (या सिर्फ event handlers के लिए void) return करना चाहिए, इसके अंदर कभी synchronously block नहीं होना चाहिए।

उदाहरण: async / await Basics

markup
using System;
using System.Threading.Tasks;

class Program
{
    static async Task<int> ComputeAsync()
    {
        await Task.Delay(100);
        return 42;
    }

    static async Task Main(string[] args)
    {
        Console.WriteLine("Starting...");
        int result = await ComputeAsync();
        Console.WriteLine($"Result: {result}");
    }
}
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. UI code में किसी task पर .Result या .Wait() उपयोग करना, जो deadlock कर सकता है।
  2. await भूल जाना, इसलिए method task खत्म होने से पहले जारी रहता है।
  3. एक async void method लिखना, जिसे await नहीं किया जा सकता और जो exceptions छुपाता है।
🔒

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.