I'm working on a plugin project in which I'm using Eclipse background processing.
What's the difference between the syncExec() and asyncExec() methods of the Display class? In which situations are they applicable? Any example could be helpful.
from Q: Why do I get the error "org.eclipse.swt.SWTException: Invalid thread access"?
To allow background threads to perform operations on objects belonging to the UI-thread, the methods syncExec(Runnable runnable) and asyncExec(Runnable runnable) of Display are used. These are the only methods in SWT that can be called from any thread. They allow a runnable to be executed by the UI-thread, either synchronously, causing the background thread to wait for the runnable to finish, or asynchronously allowing the background thread to continue execution without waiting for the result. A runnable that is executed using syncExec() most closely matches the equivalent direct call to the UI operation because a Java method call always waits for the result before proceeding, just like syncExec().
Adding to Tom Seidel's answer, here are examples of situations where you might want to use one or the other:
Use asyncExec
when you want to update something in the UI without caring about the results. For example updating a label or a progress bar.
Use syncExec
where the code following that method call needs to be sure that the UI is in a consistent state, or needs some data from the UI. For example getting some data from a user dialog. Or you update a widget and before doing anything else (e.g. another UI update) you want to know that the widget update has completed.
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