async / await की Basics
async और await किसी program को कोई धीमा काम, जैसे download का इंतज़ार, शुरू करने और इंतज़ार के दौरान बाकी काम करने देते हैं। यह bread को toaster में डालकर juice डालने जैसा है बजाय बस घूरते रहने के।
In this page:
Syntax
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
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}");
}
}
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- UI code में किसी task पर
.Resultया.Wait()उपयोग करना, जो deadlock कर सकता है। awaitभूल जाना, इसलिए method task खत्म होने से पहले जारी रहता है।- एक
async voidmethod लिखना, जिसे await नहीं किया जा सकता और जो exceptions छुपाता है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: