找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 657|回复: 0

[理工] 简单介绍.Net3.0 中跨线程访问控件

[复制链接]

31

主题

0

回帖

151

积分

新手上路

积分
151
发表于 2008-11-4 01:40:27 | 显示全部楼层 |阅读模式
简单介绍.Net3.0 中跨线程访问控件

这两天用WPF做一个项目的UI部分时,发现跨线程地访问了UI控件,自然地报异常了。当时找了半天也没在控件中找到InvokeRequired属性和Invoke方法,郁闷之极.....最后发现在.net3.0中,这有所改变了。
  替代InvokeRequired的方法是DispatcherObject.CheckAccess()或DispatcherObject.VerifyAccess()方法,用于指示当前线程是否可以直接访问控件。
  替代Invoke的方法是DispatcherObject.Dispatcher.BeginInvoke(...)方法。
  参考代码:

  // Uses the DispatcherObject.CheckAccess method to determine if
  // the calling thread has access to the thread the UI object is on
  private void TryToUpdateButtonCheckAccess(object uiObject)
  {
   Button theButton = uiObject as Button;
  
   if (theButton != null)
   {
   // Checking if this thread has access to the object
   if(theButton.CheckAccess())
   {
   // This thread has access so it can update the UI thread
   UpdateButtonUI(theButton);
   }
   else
   {
   // This thread does not have access to the UI thread
   // Pushing update method on the Dispatcher of the UI thread
   theButton.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
   new UpdateUIDelegate(UpdateButtonUI), theButton);
   }
   }
  }

          专注所以专业,专业所以值得信赖。
╔┄┄┄┄┄╦┄┄┄┄┄╦┄┄┄┄┄╦┄┄┄┄┄╗
┆ 域名注册  ┆ 企业邮局  ┆   服务器  租用 、托管   ┆
╠┄┄┄┄┄╬┄┄┄┄┄╬┄┄┄┄┄╬┄┄┄┄┄╣
┆ 网站制作  ┆ 技术支持  ┆  网站推广 ┆  虚拟主机 ┆
╚┄┄┄┄┄╩┄┄┄┄┄╩┄┄┄┄┄╩┄┄┄┄┄╝
     在线订购: www.bl-kj.com  QQ:320092873
                     百隆竭诚为您服务
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|Discuz! X

GMT+8, 2026-12-1 12:02 , Processed in 0.020278 second(s), 20 queries .

Powered by Discuz! X5.0

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表