- Eclipse Plug-in Development:Beginner's Guide(Second Edition)
- Dr Alex Blewitt
- 335字
- 2021-07-14 10:36:27
Time for action – running on the UI thread
To execute code on the UI thread, Runnable
instances must be posted to the Display
via one of two methods, syncExec
or asyncExec
. The syncExec
method runs the code synchronously (the caller blocks until the code has been run) while the asyncExec
method runs the code asynchronously (the caller continues while the code is run in the background).
The Display
class is SWT's handle to a monitor (so a runtime may have more than one Display
object, and each may have its own resolution). To get hold of an instance, call either Display.getCurrent()
or Display.getDefault()
. However, it's much better to get a Display
from an associated view or widget. In this case, the Canvas
has an associated Display
.
- Go to the
TickTock
thread inside thecreatePartControl
method of theClockView
class. - Inside the
redraw
lambda, replace the call toclock.redraw()
with this:// clock.redraw(); clock.getDisplay().asyncExec(() -> clock.redraw());
- Run the target Eclipse instance and show the Clock View. The second hand should now update automatically.
What just happened?
This time, the event will execute as expected. One thread (TickTock
) is running in the background, and every second it posts a Runnable
to the UI thread, which then runs asynchronously. This example could have used syncExec
and the difference would not have been noticeable—but in general, using asyncExec
should be preferred unless there is a specific reason to need the synchronous blocking behavior.
The thread is in a while
loop and is guarded with a call to clock.isDisposed()
. Each SWT widget can be disposed with a call to dispose
. Once a widget is disposed, any native operating system resources are returned and any further operations will throw an exception. In this example, the Canvas
is disposed when the view is closed, which in turn disposes any components contained. As a result, when the view is closed, the Thread
automatically ceases its loop (the thread can also be aborted by interrupting it during its 1-second sleep pauses).
- 數據庫程序員面試筆試真題與解析
- TypeScript入門與實戰
- OpenShift開發指南(原書第2版)
- R語言經典實例(原書第2版)
- 趣學Python算法100例
- UI智能化與前端智能化:工程技術、實現方法與編程思想
- Java設計模式及實踐
- Mastering RStudio:Develop,Communicate,and Collaborate with R
- Java程序設計:原理與范例
- Oracle從入門到精通(第5版)
- Instant Ext.NET Application Development
- 數據結構與算法分析(C++語言版)
- C語言程序設計簡明教程:Qt實戰
- Managing Microsoft Hybrid Clouds
- SQL Server 入門很輕松(微課超值版)