[此文来源于互联网,牛C网只负责收集整理]
这两天用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);
}
}
}
// 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);
}
}
}
作者:gdgzboy@牛C网
地址:http://www.niuc.net/post/1349/
版权所有。转载时必须以链接形式注明作者和原始出处及本声明!
牛C网推荐您再看看以下日志:
ASP.NET XML打造网络硬盘
在C#中利用DirectX实现声音播放
asp.net 2.0中的URL重写以及urlMappings问题
ASP.NET 2.0移动开发之设备筛选器的应用
.NET在SQL Server中的图片存取技术
xml在asp.net页面中的多种展示方法
VB.Net编程实现Web Service的基础
ASP.NET 2.0中创建内容页
ASP.NET中的HTTP模块和处理程序
ASP.NET 2.0写无限级下拉菜单
ASP.NET XML打造网络硬盘
在C#中利用DirectX实现声音播放
asp.net 2.0中的URL重写以及urlMappings问题
ASP.NET 2.0移动开发之设备筛选器的应用
.NET在SQL Server中的图片存取技术
xml在asp.net页面中的多种展示方法
VB.Net编程实现Web Service的基础
ASP.NET 2.0中创建内容页
ASP.NET中的HTTP模块和处理程序
ASP.NET 2.0写无限级下拉菜单
C#学习 无废话C#设计模式之一-开篇
ASP.Net基础学习 HTML控件 简单介绍





