Single-Threaded Application with Long-Running Calculation Sample

[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

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 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 - Windows Presentation Foundation Security

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, load the sample solution or project file and then press CTRL+SHIFT+B.

Running the Sample

  • To run the compiled sample from the build environment command window, execute the .exe file in the Bin\Debug or Bin\Release folder contained under the sample source code folder.

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

See Also

Tasks

Weather Service Simulation via Dispatcher Sample

Multithreading Web Browser Sample

Disable Command Source via System Timer Sample

Concepts

Threading Model