← Back to Swift Course | Chapter 13: Concurrency | Lesson 2 of 6

Task के Basics

एक Task काम की एक छोटी unit है जिसे आप शुरू करते हैं जो अपने आप चलती है, आपके program को इसे शुरू करने और आगे बढ़ने देते हुए।
Syntax
swift
Task {
    let result = await asyncFunction()
}

let task = Task { return value }
let value = await task.value

Starting a Task

Task { } asynchronous work का एक नया block तुरंत launch करता है, जो खुद await calls शामिल कर सकता है।

उदाहरण: Starting a Task

markup
func computeSquare(_ n: Int) async -> Int {
    return n * n
}

let task = Task {
    return await computeSquare(6)
}
let result = await task.value
print("Square: \(result)")

Awaiting a Task's Value

एक Task की .value property task खत्म होने तक suspend होती है और फिर इसका result yield करती है, आपको concurrent work का outcome retrieve करने देते हुए।

उदाहरण: Awaiting a Task's Value

markup
let task = Task { () -> String in
    return "Task finished"
}
let outcome = await task.value
print(outcome)
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 { } closure के अंदर code asynchronously चलता है और इसके बाद की अगली line तक खत्म न हुआ हो।
  2. किसी Task का result इसकी .value property access किए बिना await करने की कोशिश करना।
  3. कई unstructured Task { } instances बनाना जब async let या एक task group जैसा एक structured concurrency construct safer और manage करना आसान होता।
चैप्टर सारांश
  • Task { } asynchronous work की एक नई unit शुरू करता है।
  • एक Task की .value property को इसका eventual result retrieve करने के लिए await किया जा सकता है।
  • Tasks जहां बनाए जाते हैं वहां से priority और context inherit करते हैं, लेकिन independently चलते हैं।
  • Unstructured tasks simple हैं लेकिन related work के लिए structured concurrency (task groups, async let) अक्सर पसंद की जाती है।
🔒

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.