简单介绍.Net3.0中跨线程访问控件

王朝学院·作者佚名  2016-08-28  
宽屏版  字体: 小 | 中 | 大 | 超大  

这两天用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);

}

}

}

转载自:http://www.aspnetjia.com/Cont-172.html

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有