简单介绍.Net3.0 中跨线程访问控件
2024-09-20 05:00:56
这两天用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);
}
}
}
最新文章
- office project 激活
- Centos 用户登录失败N次后锁定用户禁止登陆
- python-操作csv文件
- 转!mysql 查询 distinct多个字段 注意!!
- (转)从Membership 到 .NET4.5 之 ASP.NET Identity
- C语言知识总结(2)
- apache开源项目--Derby
- angularJS友好URL实现 good
- Android 使用动态载入框架DL进行插件化开发
- Android 7.1 屏幕旋转流程分析
- 认识 Linux 文件权限
- JDK源码分析(6)之 LinkedHashMap 相关
- leetcode日记 HouseRobber I II
- 计算机网络一:OSI七层、TCP/IP五层与TCP/IP四层
- poj1845(逆元+快速幂)
- ZOJ 3537 Cake 求凸包 区间DP
- 补装老版本的Java SE
- Storm的并行度、Grouping策略以及消息可靠处理机制简介
- java基础知识 学习 关于URL中传递的参数含有特殊字符
- [Xcode 实际操作]七、文件与数据-(19)颜色集(Color Set)的使用
热门文章
- 修改maven一更新jre就变成1.5版本
- 文件系统管理 之 Linux 创建文件系统及挂载文件系统流程详解
- A/B测试
- LeetCode: Unique Binary Search Trees II 解题报告
- Winform下richtextbox截图实现
- 【Xamarin报错】 COMPILETODALVIK : UNEXPECTED TOP-LEVEL error java.lang.OutOfMemoryError: Java heap space
- iOS开发-Xcode升级后插件失效解决办法
- POJ 2676 Sudoku
- [转] 关于hibernate的缓存使用
- 图文安装Windows Template Library - WTL Version 9.0