共用方式為


Single Threaded Application With Long Running Calculation Sample

This sample demonstrates how to keep the UI from becoming non-responsive in single threaded application which performs a long operation.

This sample has a Button which when clicked starts calculating prime numbers. This calculation is theoretically unending, so if the event handler simple went into a loop and started calculating prime numbers, the call would never return and the UI thread would freeze.

To avoid this, the sample queues an asynchronous job onto the Dispatcher of the UI thread by calling BeginInvoke. The job that is pushed on the queue processes one number when the UI thread is in the SystemIdle state and pushes another call on the dispatcher to process the next number the next time the UI thread is idle.

This insures that the UI thread will always take precedence over calculating the next number and it keeps the UI from hanging.

See the Windows Presentation Foundation Threading Model topic for a discussion on this sample.

This sample demonstrates a specific feature of the Windows Presentation Foundation and, consequently, does not follow application development best practices. For comprehensive coverage of Windows Presentation Foundation (WPF) and Microsoft .NET Framework application development best practices, refer to the following as appropriate:

Accessibility - Accessibility Best Practices

Localization - WPF Globalization and Localization Overview

Performance - Optimizing WPF Application Performance

Security - WPF Security

Download sample

Building the Sample

  • Install the Windows Software Development Kit (SDK) and open its build environment command window. On the Start menu, point to All Programs, Microsoft Windows SDK, and then click CMD Shell.

  • Download the sample, usually from the software development kit (SDK) documentation, to your hard disk drive.

  • To build the sample from the build environment command window, go to the source directory of the sample. At the command prompt, type MSBUILD.

  • To build the sample in Microsoft Visual Studio 2005, load the sample solution or project file and then press CTRL+SHIFT+B.

Running the Sample

  • To run the compiled sample with debugging in Visual Studio 2005, press F5.

See Also

Other Resources

Windows Presentation Foundation Threading Model
Weather Service Simulation Via Dispatcher Sample
Multithreading Web Browser Sample
Disable Command Source Via System Timer Sample