One of the most common tasks you need to perform in a Windows Phone application is updating the UI from a separate thread.
For example, you may be download some content asynchronously using a WebClient class and when the operation is completed, you want to update the UI with the content that was downloaded. Updating the UI directly from an asynchronous thread is not allowed, as UI controls are not thread-safe.
The easiest way to update the UI from an asynchronous thread is to use the Dispatcher class. To determine if you can update an UI directly, you can use the CheckAccess() method. If this method returns a true, it means you can directly update the UI. Else, you have to use the BeginInvoke() method of the Dispatcher class to update the UI in a thread-safe manner. The following code snippet makes this clear:
if (Dispatcher.CheckAccess() == false)
{
//---you have to update the UI through the BeginInvoke() method---
Dispatcher.BeginInvoke(() =>
txtStatus.Text = "Something happened..."
);
}
else
{
//---you can update the UI directly---
txtStatus.Text = "Something happened..."
}
If you have more than one statement to perform in the BeginInvoke() method, you can group them into a method and call it like this:
private void UpdateUI(String text)
{
txtStatus.Text = text;
btnLogin.Content = text;
}
...
...
Dispatcher.BeginInvoke(() =>
UpdateUI("Something happened...")
);
本文详细介绍了在Windows Phone应用中如何从异步线程安全地更新用户界面。通过使用Dispatcher类,文章解释了如何检查线程访问权限并决定是否直接更新UI或使用BeginInvoke方法进行线程安全更新。此外,还展示了如何在BeginInvoke方法中执行多条语句,并提供了一个实例代码片段来清晰说明整个过程。
1145

被折叠的 条评论
为什么被折叠?



