![](/img/trans.png)
[英]Does a non suspend function inside a coroutine still run on another thread?
[英]does launch coroutine builder cause suspend functions to run on new thread?
最近開始使用 Kotlin 協程
這是語法:
main(){
launch(Dispatchers.Main){
delay(2000)
print("inside coroutine")
}
print("outside coroutine")
}
我知道首先打印外部協程,然后打印內部協程,因為延遲是暫停 function 並且它僅阻止協程而不是線程本身。
但是由於協程需要在其他地方(例如在不同的線程上)執行才能知道何時恢復,所以這是如何處理的?
它可以是任何進程強烈暫停 function 而不是延遲。
唯一我不明白的是,無論啟動{}構建器中提供的調度程序如何,掛起 function 是否實際上在引擎蓋下的不同線程上運行?
delay() function 在后台異步運行。 如果使用 Dispatchers.Main 運行,其他掛起函數會阻塞線程
suspend
函數旨在阻止當前協程,而不是線程,這意味着它們應該在后台線程中運行。 例如delay
function 在給定時間內阻塞協程而不阻塞線程,並在指定時間后恢復它。 您可以創建一個在后台線程上運行的suspend
function,如下所示:
suspend fun someSuspendFun() = withContext(Dispatchers.IO) {
// do some long running operation
}
使用withContext(Dispatchers.IO)
我們將 function 執行的上下文切換到后台線程。 withContext
function 也可以返回一些結果。
要調用 function,我們可以使用協程構建器:
someScope.launch(Dispatchers.Main){
someSuspendFun() // suspends current coroutine without blocking the Main Thread
print("inside coroutine") // this line will be executed in the Main Thread after `someSuspendFun()` function finish execution.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.