java 如何使用IntelliJ插件SDK取消Task.Backgroundable

sbtkgmzw  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(249)

如果我创建了一个后台任务,这样...我可以通过点击“X”在UI中取消它...但是,我也希望能够取消它编程。

public class MyTaskLauncher {
     public Map<String, Task.Backgroundable> myTasks = new HashMap<>();
     public myTaskLaunchMethod(){
         Task.Backgroundable myBgTask = new Task.Backgroundable(null, "MyTask", true, null) {

                @Override
                public void onCancel() {
                    super.onCancel();
                    System.out.println("cancelling")
                }

                @Override
                public void onFinished() {
                    super.onFinished();
                }

                @Override
                public void run(@NotNull ProgressIndicator progressIndicator) {
                    
                    //do some work that I want to cancel programmatically somewhere else in my code
                }
            };

            Log.trace("Starting task...");
            ProgressManager.getInstance().run(myBgTask);
            myTasks.put("task1", myBgTask);
      }
 }

现在任务运行,但如果发生特定事件,我需要立即停止该任务。

// somewhere else in my code, functionality I'm looking for.
     MyTaskLauncher.myTasks.get("task1").CancelTask()
2wnc66cl

2wnc66cl1#

当您从run()方法抛出ProcessCanceledException时,回调将被取消。然后将执行onCancel()中的代码。
Task接口中onCancel()方法的定义和JavaDoc:

/**
 * This callback will be invoked on AWT dispatch thread.
 * <p>
 * Callback executed when run() throws {@link ProcessCanceledException} or if its {@link ProgressIndicator} was canceled.
 */
public void onCancel() { }

相关问题