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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With