开发者

Display.getCurrent().asyncExec not run in parallel?

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?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜