Java 在IntelliJ插件中创建后台任务
我正在开发一个IntelliJ idea插件,希望在后台任务中运行代码(在后台任务对话框和UI以外的其他线程中可见) 我发现了以下内容,并通过传递一个可运行对象并实现其运行方法进行了尝试,但它仍然阻塞了UI,当我尝试自己执行线程时,我得到了以下错误Java 在IntelliJ插件中创建后台任务,java,intellij-idea,intellij-plugin,Java,Intellij Idea,Intellij Plugin,我正在开发一个IntelliJ idea插件,希望在后台任务中运行代码(在后台任务对话框和UI以外的其他线程中可见) 我发现了以下内容,并通过传递一个可运行对象并实现其运行方法进行了尝试,但它仍然阻塞了UI,当我尝试自己执行线程时,我得到了以下错误 Read access is allowed from event dispatch thread or inside read-action only (see com.intellij.openapi.application.Applicati
Read access is allowed from event dispatch thread or inside read-action only (see com.intellij.openapi.application.Application.runReadAction())
Details: Current thread: Thread[Thread-69 [WriteAccessToken],6,Idea Thread Group] 532224832
Our dispatch thread:Thread[AWT-EventQueue-1 12.1.4#IU-129.713, eap:false,6,Idea Thread Group] 324031064
SystemEventQueueThread: Thread[AWT-EventQueue-1 12.1.4#IU-129.713, eap:false,6,Idea Thread Group] 324031064
这是一般的解决办法
ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
public void run() {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
// do whatever you need to do
}
});
}
});
我找到了一种更好的方法,可以将进程作为后台任务运行,在这里可以更新进度条百分比和文本
ProgressManager.getInstance().run(new Task.Backgroundable(project, "Title"){
public void run(@NotNull ProgressIndicator progressIndicator) {
// start your process
// Set the progress bar percentage and text
progressIndicator.setFraction(0.10);
progressIndicator.setText("90% to finish");
// 50% done
progressIndicator.setFraction(0.50);
progressIndicator.setText("50% to finish");
// Finished
progressIndicator.setFraction(1.0);
progressIndicator.setText("finished");
}});
如果您需要从另一个线程读取一些数据,您应该使用
AccessToken token = null;
try {
token = ApplicationManager.getApplication().acquireReadActionLock();
//do what you need
} finally {
token.finish();
}
如API中所述:
导致在AWT事件上异步执行doRun.run()
调度线程。这将在所有挂起的AWT事件发生后发生
已经处理过了。当应用程序线程
需要更新GUI
使用kotlin运行后台任务的新方法
import com.intellij.openapi.progress.runBackgroundableTask
runBackgroundableTask(“我的背景任务”,项目){
对于(0..10步骤1中的i){
it.checkcancelled()
it.fraction=i/10.0
睡眠(i*100L)
}
}
您可以添加更多关于如何取消进度指示器的代码,以及如何使用令牌更改UIS的代码吗?应该将这些代码保存在哪里,以便在构建完成后立即执行这些代码?虽然这些代码可以解决问题,但如何以及为什么解决这些问题将真正有助于提高您的帖子质量,而且可能会得到更多的支持票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请编辑您的答案,添加解释,并说明适用的限制和假设。
SwingUtilities.invokeLater {
// do something
}