所以我有一段有趣的代码,然后我遇到了一个OutOfMemoryError。
所以我的问题是,我在我的searchThread中创建了新的线程,这些线程又在搜索。这之前创建了一个OutOfMemoryError,但是我想使用TornadoFX代码来解决这个问题,没有任何幸运。
searchThread = runAsync {
while (!searchThread.isCancelled) {
runAsync {
// Searching for Sth
} ui {
// Updating UI
}
}
}
}如果我的搜索线程中的runAsync仍在运行,我如何才能跳过创建新线程的过程?
发布于 2019-09-23 23:26:20
你正在做的事情是在一个紧凑的循环中创建新任务,所以很明显你会耗尽内存。对嵌套runAsync的调用不会等待,只需再次执行,直到条件为假。
删除内部的runAsync并执行您想做的任何事情,然后如果您想要更新UI线程上的某些内容,则调用runLater。
发布于 2019-09-26 05:48:23
我想我理解你的问题。您的目标是只有一个搜索线程,如果它已经在运行,就不会被调用。就像Edvin说的,循环调用异步线程真的很糟糕。更不用说,嵌套的线程甚至可能没有终止条件。这将是一个简单的解决方案,但这不是更有意义吗?:
val searchTask: Task<YourReturnType>? = null
private fun search() {
if(searchTask?.isRunning != true) {
searchTask = runAsync {
//Do your search thread things
} ui { result ->
//do things with your UI based on your result
}
}
}类似地,如果你想用一个新的搜索线程替换一个旧的运行中的搜索线程,你可以尝试如下所示:
val searchTask: Task<YourReturnType>? = null
private fun search() {
if(searchTask?.isRunning == true) {
searchTask?.cancel()
//You should probably do something to check if the cancel succeeded.
}
searchTask = runAsync {
//Do your search thread things
} ui { result ->
//do things with your UI based on your result
}
}https://stackoverflow.com/questions/58065168
复制相似问题