Threading Model IN WPF ------------ Consolidated from MSDN

原创 2007年09月30日 15:25:00

No matter how well architected, no UI framework will ever be able to provide a single threaded solution for every sort of problem. WPF comes close, but there are still situations where multiple threads improve user interface (UI) responsiveness or application performance. After discussing some background material, this paper will explore some of these situations. We’ll finish with a discussion of some lower level details for the particularly curious.

Overview and the Disptacher
Typical, WPF applications start their lives with two threads: one for handling rendering and another for managing the UI. The rendering thread effectively runs hidden in the background while the UI thread receives input, handles events, paints the screen, and runs application code. Most applications use a single UI thread, although in some situations it is best to use several. We’ll discuss this with an example later in the paper.

The UI thread queues work items inside an object called a Dispatcher. The Dispatcher selects work items on a priority basis and runs each one to completion. Every UI thread must have at least one Dispatcher and each Dispatcher can execute work items in exactly one thread.

The trick to building responsive, friendly applications is to maximize the Dispatcher throughput by keeping the work items small. This way items never get stale sitting in the Dispatcher queue waiting for processing. Any perceivable delay between input and response can frustrate a user.

How then are WPF applications supposed to handle big operations? What if my code involves a large calculation or needs to query a database on some remote server? Usually, the answer is to handle the big operation in a separate thread, leaving the UI thread free to tend to items in the Dispatcher queue. When the big operation completes, it can report its result back to the UI thread for display.

Historically, Windows only allows UI elements to be accessed by the thread that created them. This means that a background thread in charge of some long running task can’t update a textbox when it’s done. Windows does this to ensure the integrity of UI components. A listbox could turn out looking very strange if its contents were updated by a background thread during painting.

WPF has a built in mutual exclusion mechanism that enforces this. Just about every class in WPF descends from DisptcherObject. At construction, a DisptcherObject stores a reference to the Dispatcher linked to the currently running thread. In effect, the DisptcherObject associates with the thread that creates it. During program execution, a DisptcherObject can call its public VerifyAccess method. VerifyAccess examines the Dispatcher associated with the current thread and compares it to the Dispatcher reference stored during construction. If they don’t match, VerifyAccess throws an exception. VerifyAccess is intended to be called at the beginning of every method belonging to a DisptcherObject.

If only one thread can modify the UI how do background threads interact with the user? A background thread can ask the UI thread to perform an operation on its behalf. It does this by registering a work item with the Dispatcher of the UI thread. The Dispatcher class provides two methods for registering work items: Invoke and BeginInvoke. Both methods schedule a delegate for execution. Invoke is a synchronous call – that is, it doesn’t return until the UI thread actually finishes executing the delegate. BeginInvoke is asynchronous and returns immediately.

the Dispatcher orders the elements in its queue by priority. There are ten levels that may be specified when adding an element to the Dispatcher queue. These priorities are maintained in the DispatcherPriority enumeration. Detailed information about DispatcherPriority levels can be found in the Windows SDK documentation. 

Example:

XAML

<Grid>
        
<Grid.RowDefinitions>
            
<RowDefinition Height="50"/>
            
<RowDefinition Height="50"/>
        
</Grid.RowDefinitions>
    
<ProgressBar Margin="120,12,99,15" Name="progressBar1" Value="100" />
    
<Button Grid.Row="1" Margin="147,17,155,10" Name="button1" Click="button1_Click">Button</Button>
  
</Grid>

CS 

public partial class Window1 : System.Windows.Window
    
...{
        
public delegate void AscCall();

        
public Window1()
        
...{
            InitializeComponent();
        }


        
void button1_Click(object sender, RoutedEventArgs e)
        
...{
            
/**//* The first way of AscCall */
            AscCall acall 
= new AscCall(DoLargeBlock);
            acall.BeginInvoke(
nullnull);

            
/**//* The second way of AscCall */
            
//ThreadStart ts = new ThreadStart(DoLargeBlock);
            
//Thread td = new Thread(ts);
            
//td.Start();
        }


        
private void DoLargeBlock()
        
...{
            System.Threading.Thread.Sleep(
5000);
            UpdateUI();
        }


        
private void UpdateUI()
        
...{
            progressBar1.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                
new AscCall(UpdatePrograbass));
            button1.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                
new AscCall(UpdateButton));
        }


        
private void UpdatePrograbass()
        
...{
            progressBar1.Value 
= 50;
        }


        
private void UpdateButton()
        
...{
            
this.button1.Content = "Done";
        }

    }

Excel 2003 实用技巧 (FROM MSDN)

Excel 2003 实用技巧 发布日期 : 1/31/2005 | 更新日期 : 1/31/2005Frank Rice Microsoft Corporation适用于: Micr...

Threading in C#

  • 2010年04月27日 18:26
  • 1.2MB
  • 下载

Threading in C#

  • 2009年11月18日 10:14
  • 431KB
  • 下载

【翻译】WPF4.5新特性(MSDN的翻译读不太懂)

我很在意WPF的发展,有人说微软不再维护WPF了,无所谓,随他去。 MSDN上有简体版:http://msdn.microsoft.com/zh-cn/library/vstudio/bb61358...

Threading in C#

  • 2009年09月17日 15:09
  • 564KB
  • 下载

Threading in C#(中).pdf

  • 2009年10月22日 10:42
  • 655KB
  • 下载

MSDN Kernel-Mode Driver Architecture学习笔记(2)——Windows Driver Model (1)

为了让驱动程序开发者编写的设备驱动可以在源代码上兼容所有的微软Windows操作系统,引入了Windows Driver Model(WDM=Windows驱动程序模型)。符合WDM规则的内核模式驱动...
  • HOOKTTG
  • HOOKTTG
  • 2011年04月15日 14:57
  • 938

Threading in C#

  • 2011年04月19日 16:19
  • 1.16MB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Threading Model IN WPF ------------ Consolidated from MSDN
举报原因:
原因补充:

(最多只允许输入30个字)