Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 854
CaiNiaoCoder Avatar asked Jan 20 '23 00:01

CaiNiaoCoder


2 Answers

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.

like image 54
Edward Thomson Avatar answered Feb 11 '23 15:02

Edward Thomson


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.

like image 37
PhilJ Avatar answered Feb 11 '23 14:02

PhilJ