[英]Kotlin Coroutines - Different options for using Coroutine Scope/Context?
我是 Kotlin/Coroutines 的新手,我注意到使用CoroutineScope
兩種不同方式。
選項 1 如下,在任何函數中:
CoroutineScope(Dispatchers.Default).launch {
expensiveOperation()
}
選項 2 是通過在您的類中實現CoroutineScope
接口,覆蓋CoroutineContext
,然后您可以使用launch
或async
輕松啟動協程:
@Service
class ServiceImpl() : CoroutineScope {
override val coroutineContext: CoroutineContext
get() = Dispatchers.Default + Job()
fun someFunction() {
launch {
expensiveOperation()
}
}
}
我目前正在開發一個后端端點,它將執行以下操作:
這兩個用例有什么區別,對於這個場景,哪個是獲取CoroutineScope
的首選方法?
這個端點每秒可能會收到多個請求,冗長的操作需要一兩分鍾,所以肯定會有多個請求同時處理,來自各種請求。
另外,如果是選項 2,我是否要將范圍/上下文傳遞給執行繁重處理的函數? 或者這是不必要的? 例如:
類 ServiceImpl() : CoroutineScope {
override val coroutineContext: CoroutineContext
get() = Dispatchers.Default + Job()
fun someFunction() {
launch {
expensiveOperation(CoroutineScope(coroutineContext))
}
}
private fun expensiveOperation(scope: CoroutineScope)
{
// perform expensive operation
}
}
這是一個 Spring Boot 應用程序,我使用的是Kotlin
1.3
版。
如果您對如何最好地構建此服務類有任何想法/建議,請告訴我。 謝謝
我會推薦選項 2。它會讓你有機會為你的所有協程明確定義父Job
。 這也提供了正確關閉整個執行的機會。
還有幾個協程上下文鍵要包括 - CoroutineName
, CoroutineExceptionHandler
等等。
最后,如果您顯式傳遞CoroutineScope
和關聯的 Job,結構並發可能會更好地工作。
https://medium.com/@elizarov/structured-concurrency-722d765aa952
另外,看看羅馬表格的解釋: https : //medium.com/@elizarov/coroutine-context-and-scope-c8b255d59055
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.