We will post a blog series to introduce multi-threading programming in Windows Store app. In this blog series, we will walk through a sample together to demonstrate which multi-threading APIs can be used, how to create a thread, and synchronization.
In this blog, we will introduce which Win32 multi-threading APIs can be used in Windows Store apps, and how to create threads.
We need to rewrite some code in order to migrate multi-threading code from a traditional .Net applicaton to a Windows Store app.
CreateThread and CreateThreadPool cannot be used in C++/CX Windows Store app.
Thread class cannot be used in .NET Windows Store app.
Only some of the synchronization APIs can be used. Here lists some commonly used APIs,
In the following section we will use a sample to demonstrate multi-threading Windows Store app. In the canvas, there is a ball, which moves when we click a button.
The code is in C++/CX.
Firstly, we create an empty Windows Store app project.
Then, we drag in a Canvas, an Ellipse, and a Button. Below is the xaml code,
<Canvas x:Name="canvas" HorizontalAlignment="Left" Height="499" Margin="143,191,0,0" VerticalAlignment="Top" Width="1046" Background="Bisque">
<Ellipse x:Name="round1" Height="100" Canvas.Left="579" Canvas.Top="254" Stroke="Black" Width="100" Fill="Turquoise"/>
<Button Content="Start" HorizontalAlignment="Left" Margin="701,97,0,0" VerticalAlignment="Top" Height="48" Width="100" Click="Button_Click_Start"/>
After that, we add a method UserTHreadMoveBall to MainPage class, and invoke the method on Button_Click_1.
auto timerDelegate = [this](IAsyncAction^ workItem)
auto uiDelegate = [this]()
ref new Windows::UI::Core::DispatchedHandler(uiDelegate));
Windows::System::Threading::ThreadPool::RunAsync(ref new Windows::System::Threading::WorkItemHandler(timerDelegate),Windows::System::Threading::WorkItemPriority::Normal);
Now, we can compile and run the code. When we click the button, the ball will move one-step leftward.
Let’s first see Windows::System::Threading::ThreadPool::RunAsync().
This API allows us run a work item using a thread pool thread.
The parameter Windows::System::Threading::WorkItemHandler is where we can pass in the work item, which can be a method or lambda expression. The second paremeter is used to set the priority of the work item.
Let’s see our Lambda expression, Dispatcher->RunAsync() is used to manipulate UI elements in non-UI thread. In the Windows Store app, we cannot manipulate UI elements in non-UI threads. So Dispatcher->RunAsync() method allow us to move the ball in non-UI thread. The paremeters are similar as ThreadPool:RunAsync, a work item and a priority.
(To be continued)