score:1

Accepted answer

executing display.syncexec/asyncexec is safe from any thread (including the ui thread), but it isn't always the best route. for instance, asyncexec will always add your runnable into the queue to execute later even if you are already on the ui thread. depending on your usecase, that may or may not be desirable. often, if you known you are already on the ui thread, it is better to just go ahead and execute the work item.

i like to use the following snippet in any method that needs to update ui and may be called from a non-ui thread. if called from ui thread, it executes the work immediately. if called from other thread, it uses asyncexec to schedule work in the next batch without blocking the calling thread.

public void task()
{
    if( this.display.getthread() != thread.currentthread() )
    {
        this.display.asyncexec
        (
            new runnable()
            {
                public void run()
                {
                    task();
                }
            }
        );

        return;
    }

    // do whatever needs to be done with the ui.
}

score:1

executing display.syncexec/asyncexec should be safe when called from any thread, no matter whether it's ui or not.

one might suspect that calling syncexec from the ui thread results in a deadlock. this is not the case since the syncexec method checks first whether the calling thread is the ui thread. if so, the run method of the runnable is executed immediately.


Related Query

More Query from same tag