Most user interface (UI) toolkits are single-threaded and SWT is no exception. This means that UI objects must be accessed exclusively from a single thread, the so-called UI thread. On the other hand, long running tasks should be executed in background threads in order to keep the UI responsive. This makes it necessary for the background threads to enqueue updates to be executed on the UI thread instead of accessing UI objects directly.
To schedule code for execution on the UI thread, SWT offers the Display asyncExec() and syncExec()methods.
Display asyncExec vs syncExec
While both methods enqueue the argument for execution on the UI thread, they differ in what they do afterwards (or don’t). As the name suggests, asyncExec() works asynchronously. It returns right after the runnable was enqueued and does not wait for its execution. Whereas syncExec() is blocking and thus does wait until the code has been executed.As a rule of thumb, use asyncExec() as long as you don’t depend on the result of the scheduled code, e.g. just updating widgets to report progress. If the scheduled code returns something relevant for the further control flow – e.g. prompts for an input in a blocking dialog – then I would opt for syncExec().
If, for example, a background thread wants to report progress about the work done, the simplest form might look like this: