具有 UI 访问权限的 Eclipse 作业

Eclipse job with UI access

我有一种情况。 我有一个 Eclipse 作业,代码如下:

private class ExecutionJob extends Job {
    public static final String MY_FAMILY = "myJobFamily";

    public ExecutionJob(String name) {
        super(name);
    }

    @Override
    protected IStatus run(IProgressMonitor monitor) {
        monitor.beginTask("executing ...... ", IProgressMonitor.UNKNOWN);
        methodForExecution();
        monitor.done();
        return Status.OK_STATUS;
    }

    @Override
    public boolean belongsTo(Object family) {
        return family == MY_FAMILY;
    }
}

而这个 methodForExecution() 的代码如下:

public void methodForExecution(){
  PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("view_id");
}

现在的情况是,job 打开了类似 progressmonitor 的东西,我的方法试图访问 UI,它实际上在这个作业的 progressmonitor 后面。它给出 NullPointerException 因为进度监视器没有 ActiveWorkbenchWindow。

我不能使用 UIJob,因为我必须异步执行此 methodForExecution()。 有人可以帮我解决这个问题吗?

你想要的代码 运行 必须 运行 在 UI thead.

如果作业中的大部分工作都在更新 UI 并且没有长 运行ning 非 UI 代码,那么您应该使用 UIJob 来运行这个。这仍然被安排为一项工作,但 runInUIThread 方法在 UI 线程中执行。

如果你有很多非UI代码,特别是长运行ning代码,那么使用普通的Job,但你必须使用Display.asyncExec来运行 UI 线程中的方法:

Display.getDefault().asyncExec(new Runnable()
  {
    @Override
    public void run()
    {
      methodForExecution();
    }
  });

在 Java 8 中你可以做:

Display.getDefault().asyncExec(this::methodForExecution);

您也可以使用 syncExec 而不是 asyncExec 来等待 UI 更新。

如果 showView 是您想要做的全部,您可以只执行 asyncExec 而无需使用 Job