Question

I'm developing an IntelliJ-idea plugin and want to run code in background task (visible in the background tasks dialog and in another thread than the UI).

I found the following Helper class and tried it by passing a Runnable object and implement its run method but it still blocking the UI and when I tried to do the threading myself i got the following error

 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
Was it helpful?

Solution

I have found a better way to run the process as background task where you can update the progress bar percentage and text

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");

        }});

If you need to read some data from another thread you should use

AccessToken token = null;
try {
   token = ApplicationManager.getApplication().acquireReadActionLock();
                    //do what you need
} finally {
   token.finish();
}

OTHER TIPS

Here is the general solution

ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
    public void run() {
        ApplicationManager.getApplication().runReadAction(new Runnable() {
            public void run() {
            // do whatever you need to do
            }
        });
    }
});

New way to run backgroundable task with kotlin

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)
    }
}

As described in API :

Causes doRun.run() to be executed asynchronously on the AWT event dispatching thread. This will happen after all pending AWT events have been processed. This method should be used when an application thread needs to update the GUI.

SwingUtilities.invokeLater {
    // do something 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top