What is a thread pool?
In Windows Store applications the thread pool works asynchronously to complete the task in parallel. The thread pool automatically manages the set of threads in the queue and assigns an appropriate work item or piece of code to the thread when the thread is free. Normally we use the async programming model to do the work without blocking the application. The UI thread pool is also similar to that; it won't block any UI element.
In Windows Store applications we have the thread management system provided by the Windows runtime using a thread pool. The thread pool is the secure way to manage the thread because we do not have the overhead of creating a thread and destroying those threads. The thread pool manages thread creation and destruction automatically. It is better to use a built-in thread pool instead of creating our own thread pool because the built-in thread pool is defined at the OS level.
Creating Work Item and Supplying to the thread pool.
In a Windows Store application, you can create the work item using RunAsynch. This RunAsync returns an IAsyncAction object. If you need to update the UI then use CoreDispatcher.RunAsync. The following example creates the work item and assigns it to the thread pool.
- IAsyncAction ThreadPoolWorkItem = Windows.System.Threading.ThreadPool.RunAsync(
- (source) =>
- {
-
- Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High,
- () =>
- {
-
- });
- }
- }
- }
- });
In the above snippet when we call RunAsync the work item is created and has been queued to the thread pool. This work item executes when the thread is available.
Handling Work Item Completion
When you want to handle the work item completion and depending on it update the UI then you can use IAsyncAction.Completed. In async programming with a delegate we saw in the last article that we need a callback function to handle the completion like in IAsyncAction.Completed there. Have a look at the following snippet.
- ThreadPoolWorkItem.Completed = new AsyncActionCompletedHandler(
- (IAsyncAction source, AsyncStatus status) =>
- {
- Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High,
- () =>
- {
-
- });
Conclusion
Using a thread pool in a Windows Store application, we can perform the async calls in parallel.
Join the conversation! Your thoughts help the community grow.