Kotlin:协程运行滞后
Kotlin: lag in coroutine runBlocking
我正在使用 kotlin Coroutines 执行异步网络操作以避免 NetworkOnMainThreadException
。
问题是当我使用 runBlocking
时发生的滞后,需要一些时间才能完成当前线程。
如何防止这种延迟或滞后,并让异步操作无延迟地完成
runBlocking {
val job = async (Dispatchers.IO) {
try{
//Network operations are here
}catch(){
}
}
}
通过使用 runBlocking
,您将阻塞主线程,直到协程完成。
不会抛出 NetworkOnMainThread
异常,因为从技术上讲请求是在后台线程上完成的,但是让主线程等待直到后台线程完成,这同样糟糕!
要解决此问题,您可以 launch
协程,任何依赖于网络请求的代码都可以在协程内完成。这样代码可能仍然在主线程上执行,但它永远不会阻塞。
// put this scope in your activity or fragment so you can cancel it in onDestroy()
val scope = MainScope()
// launch coroutine within scope
scope.launch(Dispachers.Main) {
try {
val result = withContext(Dispachters.IO) {
// do blocking networking on IO thread
""
}
// now back on the main thread and we can use 'result'. But it never blocked!
} catch(e: Exception) {
}
}
如果您不关心结果而只想 运行 在不同的线程上编写一些代码,这可以简化为:
GlobalScope.launch(Dispatchers.IO) {
try {
// code on io thread
} catch(e: Exception) {
}
}
注意:如果您正在使用封闭 class 中的变量或方法,您仍应使用自己的作用域,以便及时取消。
我正在使用 kotlin Coroutines 执行异步网络操作以避免 NetworkOnMainThreadException
。
问题是当我使用 runBlocking
时发生的滞后,需要一些时间才能完成当前线程。
如何防止这种延迟或滞后,并让异步操作无延迟地完成
runBlocking {
val job = async (Dispatchers.IO) {
try{
//Network operations are here
}catch(){
}
}
}
通过使用 runBlocking
,您将阻塞主线程,直到协程完成。
不会抛出 NetworkOnMainThread
异常,因为从技术上讲请求是在后台线程上完成的,但是让主线程等待直到后台线程完成,这同样糟糕!
要解决此问题,您可以 launch
协程,任何依赖于网络请求的代码都可以在协程内完成。这样代码可能仍然在主线程上执行,但它永远不会阻塞。
// put this scope in your activity or fragment so you can cancel it in onDestroy()
val scope = MainScope()
// launch coroutine within scope
scope.launch(Dispachers.Main) {
try {
val result = withContext(Dispachters.IO) {
// do blocking networking on IO thread
""
}
// now back on the main thread and we can use 'result'. But it never blocked!
} catch(e: Exception) {
}
}
如果您不关心结果而只想 运行 在不同的线程上编写一些代码,这可以简化为:
GlobalScope.launch(Dispatchers.IO) {
try {
// code on io thread
} catch(e: Exception) {
}
}
注意:如果您正在使用封闭 class 中的变量或方法,您仍应使用自己的作用域,以便及时取消。