首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在IntelliJ插件中创建后台任务

在IntelliJ插件中创建后台任务
EN

Stack Overflow用户
提问于 2013-09-10 17:29:28
回答 4查看 5.2K关注 0票数 15

我正在开发一个IntelliJ插件,希望在后台任务中运行代码(在后台任务对话框中可以看到,在UI之外的线程中也可以看到)。

我找到了下面的Helper class,并通过传递一个Runnable对象并实现它的run方法来尝试它,但是它仍然阻塞UI,并且当我试图自己执行线程时,我得到了以下错误

代码语言:javascript
运行
复制
 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
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-10-31 10:11:45

我找到了一种更好的方法,可以将进程作为后台任务运行,您可以在其中更新进度条百分比和文本。

代码语言:javascript
运行
复制
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");

        }});

如果您需要从另一个线程读取一些数据,则应该使用

代码语言:javascript
运行
复制
AccessToken token = null;
try {
   token = ApplicationManager.getApplication().acquireReadActionLock();
                    //do what you need
} finally {
   token.finish();
}
票数 12
EN

Stack Overflow用户

发布于 2013-09-12 16:03:06

以下是通用的解决方案

代码语言:javascript
运行
复制
ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
    public void run() {
        ApplicationManager.getApplication().runReadAction(new Runnable() {
            public void run() {
            // do whatever you need to do
            }
        });
    }
});
票数 11
EN

Stack Overflow用户

发布于 2021-03-26 09:35:06

用kotlin运行后台任务的新方法

代码语言:javascript
运行
复制
import com.intellij.openapi.progress.runBackgroundableTask

runBackgroundableTask("My Backgrund Task", project) {
    for (i in 0..10 step 1) {
        it.checkCanceled()
        it.fraction = i / 10.0
        sleep(i * 100L)
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18725340

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档