簡體   English   中英

withTimeout() 是協程構建器嗎? 它會阻塞調用線程嗎?

[英]Is withTimeout() a coroutine builder? Does it block the calling thread?

  1. 有三個主要的協程構建器 launch、async、runBlocking。 我的問題是關於withTimeout()它是協程構建器嗎? 如果是,它會返回什么? 它的范圍是什么? 它的調度員是什么?

  2. 我有以下代碼:

     val myScope = CoroutineScope(Dispatchers.Default) runBlocking{ myScope.launch { //coroutine#1 Log.i(TAG, "First coroutine launched") } withTimeout(3000){ delay(2000) Log.i(TAG, "withTimeout block executed") } myScope.launch { //coroutine#2 Log.i(TAG, "Second coroutine launched") } }

輸出是:

First coroutine launched
withTimeout block executed
Second coroutine launched

在這里您可以看到withTimeout需要兩秒鍾才能完成任務,但在此塊之后仍然執行 coroutine#2。 這意味着withTimeout阻塞了調用線程。 如果它沒有阻塞調用線程,那么輸出應該是這樣的:

First coroutine launched
Second coroutine launched
withTimeout block executed

我對嗎? 請幫助我理解這種情況。 謝謝

withTimeout()是一個suspend函數,因此應該從協程或另一個suspend函數中調用它。

協程構建器是從正常世界到懸浮世界的橋梁。

有三個主要的協程構建器 launch、async、runBlocking。 我的問題是關於 withTimeout() 它是協程構建器嗎? 如果是,它會返回什么? 它的范圍是什么? 它的調度員是什么?

根據文檔:“在協程中運行給定的暫停代碼塊......”,我使用日志進行檢查,似乎它使用當前協程來執行代碼塊,但它也在等待它完成。 withTimeout()不是協程構建器,因為它本身就是一個suspend函數,它不是從正常世界到掛起世界的橋梁。
它返回作為最后一個參數傳遞的block返回的任何內容。 它創建另一個范圍( TimeoutCoroutine )並將其用作接收器。 它使用當前上下文的CoroutineDispatcher

這意味着 withTimeout 阻塞了調用線程

withTimeout()是一個suspend函數,它不會阻塞線程,而是掛起它啟動的協程,直到block執行完畢或超時觸發。 如果block執行的時間比提供的超時時間長,那么將拋出異常並且coroutine#2將不會被執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM