Using Dispatcher

本文通过一个错误的示例展示了如何尝试从后台任务逻辑中更新UI对象,并给出了正确的实现方式:使用Dispatcher.BeginInvoke方法来确保UI更新操作在UI线程上执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

he following code example shows how you might attempt to update the UI from your task logic.

// The Wrong Way to Update a UI Object
public void btnGetTime_Click(object sender, RoutedEventArgs e)
{
   Task.Run(() => 
      {
         string currentTime = DateTime.Now.ToLongTimeString();
         SetTime(currentTime);
      }
}
private void SetTime(string time)
{
   lblTime.Content = time;
}

If you were to run the preceding code, you would get an InvalidOperationException exception with the message ”The calling thread cannot access this object because a different thread owns it.” This is because the SetTime method is running on a background thread, but the lblTime label was created by the UI thread. To update the contents of the lblTime label, you must run the SetTime method on the UI thread.

To do this, you can retrieve the Dispatcher object that is associated with the lblTime object and then call the Dispatcher.BeginInvoke method to invoke the SetTime method on the UI thread.

The following code example shows how to use the Dispatcher.BeginInvoke method to update a control on the UI thread.

// The Correct Way to Update a UI Object
public void buttonGetTime_Click(object sender, RoutedEventArgs e)
{
   Task.Run(() => 
      {
         string currentTime = DateTime.Now.ToLongTimeString();
         lblTime.Dispatcher.BeginInvoke(new Action(() => SetTime(currentTime)));
      }
}
private void SetTime(string time)
{
   lblTime.Content = time;
}

Note that the BeginInvoke method will not accept an anonymous delegate. The previous example uses the Action delegate to invoke the SetTime method. However, you can use any delegate that matches the signature of the method you want to call.

转载于:https://www.cnblogs.com/qixue/p/7365772.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值