Task के Basics
एक Task काम की एक छोटी unit है जिसे आप शुरू करते हैं जो अपने आप चलती है, आपके program को इसे शुरू करने और आगे बढ़ने देते हुए।
In this page:
Syntax
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
func computeSquare(_ n: Int) async -> Int {
return n * n
}
let task = Task {
return await computeSquare(6)
}
let result = await task.value
print("Square: \(result)")
Login to try C/C++/Java/PHP code in the editor
Awaiting a Task's Value
एक Task की .value property task खत्म होने तक suspend होती है और फिर इसका result yield करती है, आपको concurrent work का outcome retrieve करने देते हुए।
उदाहरण: Awaiting a Task's Value
let task = Task { () -> String in
return "Task finished"
}
let outcome = await task.value
print(outcome)
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. #}
आम गलतियां
- यह भूल जाना कि एक
Task { }closure के अंदर code asynchronously चलता है और इसके बाद की अगली line तक खत्म न हुआ हो। - किसी
Taskका result इसकी.valueproperty access किए बिनाawaitकरने की कोशिश करना। - कई unstructured
Task { }instances बनाना जबasync letया एक task group जैसा एक structured concurrency construct safer और manage करना आसान होता।
चैप्टर सारांश
Task { }asynchronous work की एक नई unit शुरू करता है।- एक
Taskकी.valueproperty को इसका 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: