Update UI from an asynchronous thread

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...")

 

            );

转载于:https://www.cnblogs.com/MinieGoGo/p/3421556.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值