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

                                                      .net3.0 中跨线程访问控件  
                                                                                     周银辉

这两天用WPF做一个项目的UI部分时, 发现跨线程地访问了UI控件, 自然地报异常了. 当时找了半天也没在控件中找到InvokeRequired属性和Invoke方法, 郁闷之极.....最后发现在.net3.0中,这有所改变了.

替代InvokeRequired的方法是DispatcherObject.CheckAccess()或DispatcherObject.VerifyAccess()方法,用于指示当前线程是否可以直接访问控件.

替代Invoke的方法是DispatcherObject.Dispatcher.BeginInvoke(...)方法

参考代码:

None.gif //  Uses the DispatcherObject.CheckAccess method to determine if 
None.gif
//  the calling thread has access to the thread the UI object is on
None.gif
private   void  TryToUpdateButtonCheckAccess( object  uiObject)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    Button theButton 
= uiObject as Button;
InBlock.gif
InBlock.gif    
if (theButton != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
// Checking if this thread has access to the object
InBlock.gif
        if(theButton.CheckAccess())
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
// This thread has access so it can update the UI thread
InBlock.gif
            UpdateButtonUI(theButton);
ExpandedSubBlockEnd.gif        }

InBlock.gif        
else
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
// This thread does not have access to the UI thread
InBlock.gif            
// Pushing update method on the Dispatcher of the UI thread
InBlock.gif
            theButton.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
InBlock.gif                
new UpdateUIDelegate(UpdateButtonUI), theButton);
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值