`
yangzhao
  • 浏览: 91205 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

SWT Threading issues

阅读更多

From: http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse.platform.doc.isv/guide/swt_threading.htm


Threading issues
When working with a widget toolkit, it is important to understand the underlying thread model that is used for reading and dispatching platform GUI events. The implementation of the UI thread affects the rules that applications must follow when using Java threads in their code.

Native event dispatching
Underneath any GUI application, regardless of its language or UI toolkit, the OS platform detects GUI events and places them in application event queues. Although the mechanics are slightly different on different OS platforms, the basics are similar. As the user clicks the mouse, types characters, or surfaces windows, the OS generates application GUI events, such as mouse clicks, keystrokes, or window paint events. It determines which window and application should receive each event and places it in the application's event queue.

The underlying structure for any windowed GUI application is an event loop. Applications initialize and then start a loop which simply reads the GUI events from the queue and reacts accordingly. Any work that is done while handling one of these events must happen quickly in order to keep the GUI system responsive to the user.

Long operations triggered by UI events should be performed in a separate thread in order to allow the event loop thread to return quickly and fetch the next event from the application's queue. However, access to the widgets and platform API from other threads must be controlled with explicit locking and serialization. An application that fails to follow the rules can cause an OS call to fail, or worse, lock up the entire GUI system.

SWT UI thread
SWT follows the threading model supported directly by the platforms. The application program runs the event loop in its main thread and dispatches events directly from this thread. The UI thread is the thread in which the Display was created. All other widgets must be created in the UI thread.

Since all event code is triggered from the application's UI thread, application code that handles events can freely access the widgets and make graphics calls without any special techniques. However, the application is responsible for forking computational threads when performing long operations in response to an event.

Note: SWT will trigger an SWTException for any calls made from a non-UI thread that must be made from the UI thread.
The main thread, including the event loop, for an SWT application has the following structure:

   public static void main (String [] args) {
      Display display = new Display ();
      Shell shell = new Shell (display);
      shell.open ();
      // start the event loop. We stop when the user has done
      // something to dispose our window.
      while (!shell.isDisposed ()) {
         if (!display.readAndDispatch ())
            display.sleep ();
      }
      display.dispose ();
   }

Once the widgets are created and the shell is opened, the application reads and dispatches events from the OS queue until the shell window is disposed. If there are no events available for us in the queue, we tell the display to sleep to give other applications a chance to run.

SWT provides special access methods for calling widget and graphics code from a background thread.

Executing code from a non-UI thread
Applications that wish to call UI code from a non-UI thread must provide a Runnable that calls the UI code. The methods syncExec(Runnable) and asyncExec(Runnable) in the Display class are used to execute these runnables in the UI thread during the event loop.

syncExec(Runnable) should be used when the application code in the non-UI thread depends on the return value from the UI code or otherwise needs to ensure that the runnable is run to completion before returning to the thread. SWT will block the calling thread until the runnable has been run from the application's UI thread. For example, a background thread that is computing something based on a window's current size would want to synchronously run the code to get the window's size and then continue with its computations.
asyncExec(Runnable) should be used when the application needs to perform some UI operations, but is not dependent upon the operations being completed before continuing. For example, a background thread that updates a progress indicator or redraws a window could request the update asynchronously and continue with its processing. In this case, there is no guaranteed relationship between the timing of the background thread and the execution of the runnable.
The following code snippet demonstrates the pattern for using these methods:

   // do time-intensive computations
   ...
   // now update the UI. We don't depend on the result,
   // so use async.
   display.asyncExec (new Runnable () {
      public void run () {
         if (!myWindow.isDisposed())
            myWindow.redraw ();
      }
   });
   // now do more computations
   ...

It is good practice to check if your widget is disposed from within the runnable when using asyncExec. Since other things can happen in the UI thread between the call to asyncExec and the execution of your runnable, you can never be sure what state your widgets are in by the time your runnable executes.

The workbench and threads
The threading rules are very clear when you are implementing an SWT application from the ground up since you control the creation of the event loop and the decision to fork computational threads in your application.

Things get a bit more complicated when you are contributing plug-in code to the workbench. The following rules can be considered "rules of engagement" when using platform UI classes, although from release to release there may be exceptions to these rules:

In general, any workbench UI extensions you add to the platform will be executing in the workbench's UI thread, unless they are specifically related to threads or background jobs (such as background job progress indication).
If you receive an event from the workbench, it is not guaranteed that it is executing in the UI thread of the workbench. Consult the javadoc for the particular class that defines the listener or event. If there is no specific documentation discussing threading, and the class is clearly a UI-related class, you may expect that the event arrives in the UI thread of the workbench.
Likewise, a platform UI library should not be considered thread-safe unless it is specifically documented as such. Note that most platform UI classes dispatch listeners from the calling thread that triggered the event. Workbench and JFace API calls do not check that the caller is executing in the UI thread.This means that your plug-in may introduce a problem if you call a method that triggers an event from a non-UI thread. SWT triggers an SWTException for all API calls made from a non-UI thread. In general, avoid calling platform UI code from another thread unless the javadoc specifically allows it.
If your plug-in forks a computational thread or uses a workbench Job, it must use the Display asyncExec(Runnable) or syncExec(Runnable) methods when calling any API for the workbench, JFace, or SWT, unless the API specifically allows call-in from a background thread.
If your plug-in uses the JFace IRunnableContext interface to invoke a progress monitor and run an operation, it supplies an argument to specify whether a computational thread is forked for running the operation.
分享到:
评论

相关推荐

    python使用threading获取线程函数返回值的实现方法

    `threading`模块是Python的标准库之一,它提供了线程管理的功能,包括创建、同步和控制线程。然而,Python的`threading`模块本身并不直接支持获取线程函数的返回值,这需要我们通过一些额外的方式来实现。以下将详细...

    .Net 3.5 使用 System.Threading.Task

    .Net 3.5 下使用的 System.Threading.Tasks。 安装完成后,添加引用时只需要在安装目录 C:\Program Files (x86)\Microsoft Reactive Extensions\Redist\DesktopV2 下找到 System.Threading.dll,添加即可

    threading.timer 实例项目源代码

    在Python的多线程编程中,`threading`模块提供了丰富的功能,其中之一就是`threading.Timer`类。这个类主要用于创建定时任务,它基于`threading.Thread`,但增加了时间延迟执行的功能。在这个实例项目中,`threading...

    C++ Threading

    ### C++ Threading:一种通用编程方法 #### 概述 C++ threading 是一个重要的主题,尤其是在现代软件开发中,多线程编程已经成为提高程序性能、实现并发处理的关键技术之一。本文将根据提供的资料深入探讨关于C++ ...

    C#多线程操作控件threading的使用

    C#多线程操作控件threading的使用 在C#中,多线程操作控件是一个常见的问题。由于控件是主线程创建的,因此不能直接从另一个线程访问。这篇文章将探讨如何使用threading来实现多线程操作控件。 首先, let's 看一...

    Threading in C# 中文版

    例如,可以使用`System.Threading.Thread`类来创建一个新的线程对象,并指定该线程将执行的方法。以下是一个创建新线程的示例: ```csharp using System; using System.Threading; class ThreadTest { static ...

    网络编程资料(socket,threading)

    在这个主题中,Socket编程和多线程(Threading)是两个核心概念,对于开发多语即时通讯软件至关重要。 首先,让我们深入了解Socket编程。Socket是网络通信中的基本组件,可以看作是两台计算机之间的通信端点。在TCP...

    threading模块

    `threading`模块是Python标准库中的一个多线程支持模块,它提供了丰富的工具来管理和控制线程间的交互。本文将深入解析`threading`模块的主要类、方法和属性,特别是`Condition`类。 首先,`TIMEOUT_MAX`是一个变量...

    Threading.pdf

    标题“Threading.pdf”暗示了文档的主题是关于C#中的线程管理,特别是.NET环境下的线程操作。文档的描述指出,这是一份专门讲述线程知识的官方文档,意味着它是围绕C#编程语言和.NET框架中的多线程编程展开的。标签...

    python多线程-threading模块.pdf

    Python 多线程 - Threading 模块 Python 中的多线程编程是使用 Threading 模块实现的,该模块提供了丰富的功能来创建和管理线程。在学习 Threading 模块之前,需要了解 Python 的基础知识,包括函数、类、对象等...

    system.Threading.Timer的使用

    在.NET框架中,`System.Threading.Timer`类是一个用于在后台线程上执行周期性操作的强大工具。这个类属于多线程编程的一部分,特别是在处理异步任务和定时触发事件时非常有用。下面我们将深入探讨`System.Threading....

    System.Threading.zip

    .Net 3.5支持Plinq的相关信息已被微软撤掉了, 而引用此dll可以使3.5的Linq支持AsParallel()方法, 3.5可以使用1.0.3058.34407版本。...using System.Threading.Tasks; using System.Threading; using System.Linq;

    C#中Forms.Timer、Timers.Timer、Threading.Timer的用法分析

    本文实例讲述了C#中Forms.Timer、Timers.Timer、Threading.Timer的用法分析,分享给大家供大家参考。具体分析如下: 在.NET Framework里面提供了三种Timer ① System.Windows.Forms.Timer ② System.Timers.Timer ③...

    Python内置库:threading(多线程操作).docx

    Python的`threading`模块是处理并发执行任务的关键工具,特别是在多核处理器的现代计算机上。这个模块提供了比旧版`thread`模块更强大的功能,包括线程管理、同步机制和丰富的类接口。在Python 2.7及以后的版本中,`...

    .NET Framework 3.5上使用System.Threading.Tasks

    我在做一个兼容WindowsXP项目时用到,用梯子到外面找来的。 由于 .NET 3.5下并没有官方实现的 Task 库,所以,是通过 VS 中 NuGet 取得的 非官方 实现的 Task 库,调用接口与官方.NET 4.0 后的应该是差不多的。

    Efficient Android Threading

    Multithreading is essential if you want to create an Android app with a great user experience, but how do you know which techniques can help solve your problem? This practical book describes many ...

    Threading in C#中文.7z

    在C#编程中,线程(Threading)是并发执行任务的一种核心机制,它允许多个操作在同一时间片内并行运行,极大地提高了程序的执行效率。尤其在处理大量数据或者进行复杂计算时,线程的使用能充分利用现代多核处理器的...

    python多线程编程示例(threading.py)

    1、多线程的理解 多进程和多线程都可以执行多个任务,线程是进程的一部分。线程的特点是线程之间可以...在Python中,同样可以实现多线程,有两个标准模块thread和threading,不过我们主要使用 更高级的threading模块。

Global site tag (gtag.js) - Google Analytics