पाठ 7 / 26

async और await

Task, async और await से non-blocking कोड लिखें और आम deadlock जालों से बचें।

Thread को ब्लॉक न करें

जब request database या HTTP call का इंतज़ार करती है, await thread को दूसरी requests के लिए मुक्त कर देता है। नतीजा आने पर method आगे बढ़ता है। इसी तरह छोटा thread pool कई users को संभालता है।

एक async method

Async method Task<T> लौटाता है। उसे await करने पर T मिलता है। यहाँ Task.Delay धीमी call की जगह है।

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

var count = await GetCountAsync();
Console.WriteLine(count);

Output:

42

.Result या .Wait() कभी नहीं

.Result या .Wait() से task पर रुकना thread बर्बाद करता है और कुछ ऐप प्रकारों में deadlock कर सकता है। पूरी call chain को async बनाएँ, और event handlers के अलावा async void से बचें।

त्वरित जाँच: बिना value लौटाने वाला async method क्या लौटाए?

  • void
  • int
  • Task
  • object
Answer

Task — `Task` लौटाएँ ताकि callers await कर सकें और exceptions पकड़ सकें। `async void` failures छिपा देता है।