.net3.0 中跨线程访问控件

                                                     .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);
        }

    }

}


posted on 2007-05-10 21:00 周银辉 阅读(3718) 评论(7)  编辑 收藏 网摘 所属分类: .NetWPF

评论

#1楼[楼主] 2007-05-10 21:47 周银辉      

补充,关于.net2.0中跨线程的控件访问,请参考这里:
http://www.cnblogs.com/zhouyinhui/archive/2006/12/05/583246.html">http://www.cnblogs.com/zhouyinhui/archive/2006/12/05/583246.html
  回复  引用  查看    

#2楼 2007-05-11 13:16 saucer[未注册用户]

参考System.Threading.SynchronizationContext类   回复  引用    

#3楼 2007-07-20 00:10 王计平[未注册用户]

好像以前在win32编程时,可以访问主线程的控件,不知道win32和managed编程方式为什么会有这种区别。
我有点懒了,一般自己如果是启动一个线程访问主线程的控件,都设置Check为false,自己注意一下互斥访问,还暂时没有什么问题,不知道理论上这种方法是不行还是不好,有高手给解答一下吗?
  回复  引用    

#4楼[楼主] 2007-07-20 09:10 周银辉      

@王计平
.net1.1中没有Control.CheckForIllegalCrossThreadCalls属性,可直接访问
.net2.0中可以直接设置成False,但不好
.net3.0中没有Control.CheckForIllegalCrossThreadCalls,但必须Invoke
  回复  引用  查看    

#5楼 2008-02-14 11:51 在线代理[未注册用户]

http://msdn2.microsoft.com/en-us/library/ms741870.aspx
这里讲的就是wpf的 thread model。
  回复  引用    

#6楼 2008-04-02 10:42 曾庆军[未注册用户]

周兄,你好呀,我叫曾庆军,想请教你一个问题,在3.0中如何使用2.0中的控件呢,比如:2.0中dataGridView如何在3.0中使用呀,谢谢了。   回复  引用    




发表评论

昵称: [登录] [注册]

主页:

邮箱:(仅博主可见)

评论内容:

  登录  注册

[使用Ctrl+Enter键快速提交评论]

0 742134




相关文章:

相关链接:

导航

<2007年5月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

统计

搜索

 

常用链接

留言簿

我参与的团队

随笔分类(215)

随笔档案(195)

友情链接

积分与排名

最新随笔

阅读排行榜