Display.getCurrent().asyncExec not run in parallel

2019-02-18 01:19发布

问题:

Here is my code:

Display.getCurrent().asyncExec(new Runnable() {
            public void run() {
                try {
                    Event e1 = new Event();
                    e1.type = EVT_CONNECTING;
                    for (Listener listener : listeners) {
                        listener.handleEvent(e1);
                    }
                    database = new Database(cp.getName(), cp.getConnection());
                    Event e2 = new Event();
                    e2.type = EVT_CONNECT_SUCCESS;
                    for (Listener listener : listeners) {
                        listener.handleEvent(e2);
                    }
                } catch (Exception ex) {
                    log.error(ex.getMessage(), ex);
                    Event e = new Event();
                    e.text = ex.getMessage();
                    e.type = EVT_CONNECT_FAILD;
                    for (Listener listener : listeners) {
                        listener.handleEvent(e);
                    }
                }
            }
        });

In above code, I try to connect to a database. Sometimes this will take a long while to give response (network connection timeout for example), but when the Runnable begin to run, the user interface lose response. Why?

回答1:

You're running this database connection Runnable on the UI thread - that means that you're starving the UI thread of processing any other messages that would cause it to paint, respond to click events, etc. So yes, while you're running this database connection job, your UI will not be able to do anything else and the UI will become unresponsive.

You probably do not want to run this database connection job on the UI thread, you probably want to do it in a simple background thread, and then post the results back up to the UI thread by using Display#asyncExec once the database connection job has finished.



回答2:

You could use Eclipse Jobs API.

Create a class that extends org.eclipse.core.runtime.jobs.Job, stick your database code in the run method then call job.schedule() to schedule and run the job.

Have a look at Lars Vogel's site for a further example.



回答3:

The point of asyncExec is to schedule something to run in the UI thread (and return immediately after scheduling), so it can't run anything in parallel.