Partager via


Best practices for using the thread pool (XAML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

This topic describes best practices for working with the thread pool.

Do's

  • Use the thread pool to do parallel work in your app.

  • Use work items to accomplish extended tasks without blocking the UI thread.

  • Create work items that are short-lived and independent. Work items run asynchronously and they can be submitted to the pool in any order from the queue.

  • Dispatch updates to the UI thread with the Windows.UI.Core.CoreDispatcher.

  • Use ThreadPoolTimer.CreateTimer instead of the Sleep function.

  • Use the thread pool instead of creating your own thread management system. The thread pool runs at the OS level with advanced capability and it is already optimized.

  • In C++, ensure that work item delegates use the agile threading model (C++ delegates are agile by default).

  • Use pre-allocated work items for critical asynchronous work.

Dont's

  • Don't create periodic timers with a period value of <1 millisecond (including 0). This will cause the work item to behave as a single-shot timer.

  • Don't submit periodic work items that take longer to complete than the amount of time you specified in the period parameter.

  • Don't do any extensive work in the UI dispatch handler. The handler provided to the UI core dispatcher runs in the UI thread.

  • Don't try to send UI updates (other than toasts and notifications) from a work item running in a background task. Instead, use background task progress and completion handlers - for example, IBackgroundTaskInstance.Progress.

  • Don't try to create work item handlers that use the async keyword. Such handlers can cause unexpected behavior by running the work item in a thread other than the one that the thread pool assigns. For example, completion handlers will run before the work item completes.

  • Don't try to run a pre-allocated work item more than once without reinitializing it.

Quickstart: Submitting a work item to the thread pool

How to submit a work item using a timer

How to create a periodic work item

How to create and use pre-allocated work items

How to respond to named events and semaphores

How to use functions as work item delegates