【问题标题】:Caused by: org.eclipse.swt.SWTException: Invalid thread access引起:org.eclipse.swt.SWTException:无效的线程访问
【发布时间】:2016-08-08 15:30:37
【问题描述】:

我在下面的代码中得到“无效的线程访问”。我不确定我在哪里写了错误的代码。我编写代码的主要目的是只显示子任务(幕后发生的事情),所以我在方法调用之前添加了子任务。

        @Override
        public void handleEvent(Event event) 
        {
            if((event.keyCode == SWT.CR || event.keyCode == 13 || event.type == SWT.Selection) && btnAdd.isEnabled())
            {
                final PreferencesMO permo = new PreferencesMO();
                permo.updatePreferences();
                permo.updateDocumentNumber();
                final ProjectMO pmo = new ProjectMO();
                final CoverSheetMO csmo = new CoverSheetMO();
                final CommonError cmerror = new CommonError();
                final ParameterConfigurationMO pamo  = new ParameterConfigurationMO();
                final SnippetNew s = new SnippetNew();
                final String projName = txtpname.getText();

                Display.getDefault().asyncExec(new Runnable() 
                {
                    public void run() 
                    {
                        try 
                        {
                            new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() {

                                @Override
                                public void run(final IProgressMonitor monitor) throws InvocationTargetException,
                                        InterruptedException 
                                {
                                    monitor.beginTask("Import Data", IProgressMonitor.UNKNOWN);

                                    monitor.subTask("Connecting to databse...");
                                    for(int i=0;i<=100;i++)
                                    {
                                        s.method1(i);
                                    }
                                    //monitor.worked(1);
                                    try { Thread.sleep(2000); } catch (Exception e) { }

                                    monitor.subTask("Analysing Data...");
                                    try { Thread.sleep(2000); } catch (Exception e) { }


                                    if(!projName.equals(""))
                                    {
                                        monitor.subTask("Updating coversheet ...");
                                        try { Thread.sleep(2000); } catch (Exception e) { }
                                        cmerror.updateCoverSheetStatusforNewProject();

                                        monitor.subTask("Inserting Project ...");
                                        try { Thread.sleep(2000); } catch (Exception e) { }
                                        pmo.addProjectManager(projName,"T");

                                        monitor.subTask("Searching Project ID ...");
                                        try { Thread.sleep(2000); } catch (Exception e) { }
                                        String p_id = pmo.searchprojectID(projName);
                                        permo.insertDocumentNumber(p_id);

                                        monitor.subTask("Inserting data into coversheet ...");
                                        try { Thread.sleep(2000); } catch (Exception e) { }
                                        csmo.insertCoversheet(p_id);

                                        pamo.insertParameterConfiguration(p_id);

                                        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setText("Demo Tool - "+projName);

                                        IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
                                        AuditLogs view = (AuditLogs) page.findView(AuditLogs.ID);
                                        IEditorPart editorPart = page.getActiveEditor();

                                        StackedLambdaChartInput input = new StackedLambdaChartInput();

                                        AnalysisResult_MetricsChartInput metricsinput = new AnalysisResult_MetricsChartInput();

                                        StackedLambdaChart_HorizantalInput stackedhorizantalinput = new StackedLambdaChart_HorizantalInput();

                                        AnalysisResult_Metrics_HorizantalChartInput metricshorizantalinput = new AnalysisResult_Metrics_HorizantalChartInput();

                                        BarChartInput inpuit = new BarChartInput();

                                        BarChart_HorizantalInput barchart_horizantalinput = new BarChart_HorizantalInput();

                                        AuditLogMO auditlog = new AuditLogMO();

                                        monitor.subTask("Fetching audit logs to display ...");
                                        try { Thread.sleep(2000); } catch (Exception e) { }

                                        java.util.List<java.util.List<String>> auditlogs = auditlog.searchAuditLog(null,null);
                                        view.table(auditlogs);
                                        try
                                         {
                                            handlerService.executeCommand(AuditLogView.ID, new Event());
                                            handlerService.executeCommand(ErrorLogView.ID, new Event());
                                            handlerService.executeCommand(DesignHierarchyHandler.ID, new Event());
                                            if(myeditor != null)
                                            {
                                                if(myeditor instanceof CoverSheet)
                                                {
                                                    handlerService.executeCommand(CoverSheetHandler.ID, new Event());
                                                }
                                                else if(myeditor instanceof ParameterConfigurations)
                                                {
                                                    handlerService.executeCommand(ParameterConfigurationHandler.ID, new Event());
                                                }
                                            }
                                         } 
                                        catch (ExecutionException | NotDefinedException | NotEnabledException | PartInitException| NotHandledException e1)
                                        {
                                            e1.printStackTrace();
                                        }
                                        Constant con = new Constant();
                                        con.createNewProject();
                                    }
                                    //shell.close();


                                    monitor.done();
                                }
                            });
                        } 
                        catch (InvocationTargetException | InterruptedException e) 
                        {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }

【问题讨论】:

  • 向我们展示堆栈跟踪并指出它是代码中的哪一行。
  • 您正试图从后台线程访问 SWT 小部件。这是不可能的。与大多数 UI 工具包一样,SWT 是单线程的,小部件只能从 UI 线程内访问。在您的情况下,请在安排作业之前阅读 txtpname 的内容,并将其存储在作业中可访问的某个位置。
  • Greg@ 当我运行它时,直到“分析数据...”。它在 "if(!txtpname.getText().equals(""))" 条件下引发错误。我已经评论了我得到错误的地方。
  • Rüdiger@ 在调用 ProgressMonitorDialog 之前,我已经在读取 txtpname 的内容了。

标签: eclipse-rcp


【解决方案1】:

把你的进度监视器如下:

Display.getDefault().asyncExec( new Runnable()
{
   IWorkbenchWindow win = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
   new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress()        {

                        @Override
                        public void run(final IProgressMonitor monitor) throws InvocationTargetException,
                                InterruptedException 
                        {
                            monitor.beginTask("Import Data", IProgressMonitor.UNKNOWN);

                            monitor.subTask("Connecting to databse...");
                            for(int i=0;i<=100;i++)

}

如果你想要工作台页面,也必须在上面的 UI 线程中调用。

【讨论】:

  • 我已经将代码包装在 asyncExec 中,但是我得到了 null。请检查我上面的代码。
  • "PlatformUI.getWorkbench().getActiveWorkbenchWindow()" 在这一行我得到空值。即使我将代码包装在 asyncExec 中,我也不应该得到它
  • 它在进度监视器的内部运行,workbenchwindow 可能会在其中返回 null,将其移至 new ProgressMonitorDialog... 上方获取 workbenchwindow ,并使用该 win 调用 getActivePagegetShell
  • 但我仍然无法访问像 getShell() 这样的 SWT 小部件和其他以下小部件。 asyncExec 不起作用。
  • 看来没有活动页面
【解决方案2】:

您无法在用于IRunnableWithProgress 代码的后台线程中访问 UI 代码。

因此,在运行进度对话框之前,您必须在 UI 线程中获取控件的值。

您也无法在后台线程中访问 IWorkbenchPage 之类的内容。如果要从非 UI 线程更新 UI 对象,则需要使用 Display.asyncExecDisplay.syncExec 在 UI 线程中运行更新代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2015-04-24
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多