org.eclipse.swt.SWTException:无效的线程访问

时间:2014-03-26 07:17:44

标签: java eclipse exception swt

我正在使用My Java Web Application(JSF)打开outlook并附加文件。 Methd只工作一次,当我再次尝试调用Method时,我得到:

org.eclipse.swt.SWTException: Invalid thread access

这是我的方法:

public void sendemails() {
        Display display = Display.getCurrent();
        Shell shell = new Shell(display);//Error is Happening on this Line.
        OleFrame frame = new OleFrame(shell, SWT.NONE);
        // This should start outlook if it is not running yet
        OleClientSite site = new OleClientSite(frame, SWT.NONE, "OVCtl.OVCtl");
        site.doVerb(OLE.OLEIVERB_INPLACEACTIVATE);
        // Now get the outlook application
        OleClientSite site2 = new OleClientSite(frame, SWT.NONE, "Outlook.Application");
        OleAutomation outlook = new OleAutomation(site2);
        OleAutomation mail = invoke(outlook, "CreateItem", 0 /* Mail item */).getAutomation();
        setProperty(mail, "BodyFormat", 2 /* HTML */);
        setProperty(mail, "Subject", "Testing");
        setProperty(mail, "HtmlBody", "I am Sending to you");
        ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
        String path = (String) ctx.getAttribute("capturepath");
        File file = new File(path);

        if (file.exists()) {
            OleAutomation attachments = getProperty(mail, "Attachments");
            invoke(attachments, "Add", path);
        } else {
            FacesContext.getCurrentInstance().addMessage(
                    null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO,
                            "Failed!",
                            "File " + path + " Does Not exists"));
        }
        invoke(mail, "Display" /* or "Send" */);
    }

环顾四周后,我发现我应该创建一个这样的方法:

public void exec() {
        Display.getDefault().asyncExec(new Runnable() {
            @Override
            public void run() {
                sendemails();
                System.out.println("Outlook called");
            }
        });
    }

我有,但当我调用exec方法时,什么也没发生。如果没有必要创建另一个方法,我可以对无效的线程访问进行排序吗?

2 个答案:

答案 0 :(得分:4)

  

我可以在没有必要的情况下对此无效的线程访问进行排序   创建另一个方法?

简而言之,没有。

长期: 需要在显示线程上调用任何更改或向SWT中的GUI添加内容的内容,否则将抛出无效的线程访问异常。您可以拨打asyncExec(Runnable)syncExec(Runnable r)

现在,通过查看this question,我认为syncExec对您来说可能是更好的选择。

答案 1 :(得分:1)

有一个解决方案:

Display.getDefault().syncExec(new Runnable(){
public void run() {
    // Your code to run Synchronously
}
});


Display.getDefault().asyncExec(new Runnable(){
public void run() {
    // // Your code to run Asynchronously
}
});