.net3.0 中跨线程访问控件
2007-05-10 21:49
134 查看
.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);
}
}
}
周银辉
这两天用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);
}
}
}
相关文章推荐
- .net3.0 中跨线程访问控件
- .net3.0 中跨线程访问控件
- 简单介绍.Net3.0 中跨线程访问控件
- .net3.0 中跨线程访问控件
- 线程间操作无效,从不是创建控件的线程访问它
- (委托事件处理)关于多线程执行显示进度条的实例(转)&&线程间操作无效: 从不是创建控件“rtxtEntryNO”的线程访问它。
- 线程间操作无效: 从不是创建控件“Control Name'”的线程访问它问题的解决方案及原理分析
- 线程间操作无效: 从不是创建控件“...”的线程访问它。
- winform 跨线程访问控件
- 【SerialPort】线程间操作无效: 从不是创建控件“txtreceive”的线程访问它。
- 线程间操作无效:从不是创建控件的线程访问它的三种方法
- WPF 线程间访问控件
- Winform线程间操作无效从不是创建控件的线程访问它的几个解决方案async和await?
- 【转】“线程间操作无效: 从不是创建控件的线程访问它”
- 线程间操作无效: 从不是创建控件“...”的线程访问它(解决方法)
- 新手老问题---------跨线程的控件访问
- c#线程问题:线程间操作无效:从不是创建控件 的线程访问它
- 如何在mfc中通过线程向主窗口发送数据或者是访问控件
- 线程间操作无效: 从不是创建控件“...”的线程访问它。
- 线程间操作无效: 从不是创建控件“textBox2”的线程访问它。