1 out of 2 rated this helpful - Rate this topic

Best practices for using the thread pool (Windows Runtime apps using C#/VB/C++ and XAML)

Applies to Windows and Windows Phone

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. This can cause unexpected behavior.

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

Related topics

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

 

 

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.