💈 A Cross-Thread Call Helper Class
Conmajia © 2012, 2018
Published on August 5th, 2012
Updated on February 2nd, 2019
Introduction
While working on background threads, you may encounter updating values of frontend GUI controls. Then you probably will face one particular problem: invalid operation between threads. As shown in figure 1, this issue throws an InvalidOperationException. It occurs every time when accesses properties/methods from other threads but the one which owns them.
In .NET Framework, version 2.0 as I refer, every Control class contains an InvokeRequired property and an Invoke method to accomplish cross-thread operations. Some typical call code is listed below.
public void DoWork() {
if (control.InvokeRequired) {
control.Invoke(DoWork);
}
else {
// do work
}
}
My Approach
I wrote a helper class InvokeHelper which granted me the power to access assets between different threads. The class has 3 methods:
Invoke()- to call methods of a control.
InvokeHelper.Invoke(<control>, "<method>"[, <param1>[,<param2>,...]]);
Get()- to get properties of a control.
InvokeHelper.Get(<control>, "<property>");
Set()- to set properties of a control.
InvokeHelper.Set(<control>, "<property>", <value>);
Demonstration
In the demo, I used a forever looping background thread (t) to show how the InvokeHelper helps threads to interact. Thread t updates the frontend thread (the GUI) every 500 milliseconds.
Thread t;
private void button1_Click(object sender, EventArgs e) {
if(t == null) {
t = new Thread(multithread);
t.Start();
label4.Text = string.Format("Thread state:\n{0}", t.ThreadState.ToString());
}
}
public void DoWork(string msg) {
this.label3.Text = string.Format("Invoke method: {0}", msg);
}
int count = 0;
void multithread() {
while(true) {
InvokeHelper.Set(this.label1, "Text", string.Format("Set value: {0}", count));
InvokeHelper.Set(this.label1, "Tag", count);
string value = InvokeHelper.Get(this.label1, "Tag")
.ToString();
InvokeHelper.Set(this.label2, "Text", string.Format("Get value: {0}", value));
InvokeHelper.Invoke(this, "DoWork", value);
Thread.Sleep(500);
count++;
}
}
Results shown in animated figure 2. Obviously, the frontend is not blocked despite t never stops.
InvokeHelper Demonstration (animation)Other Approaches
There is a built-in option in the VisualStudio IDE that disables the cross-thread access check: CheckForIllegalCrossThreadCalls. I found it slightly slower than my helper class. Figure 3 shows the test result.
CheckForIllegalCrossThreadCallsThe whole procedure of the test is recorded in figure 4. (The video lasts for 8'51")
CheckForIllegalCrossThreadCalls (8'51")Appendix
Source code of the InvokeHelper is listed below. Zipped .NET project files: Download
public class InvokeHelper {
private delegate object MethodInvoker(Control control, string methodName, params object[] args);
private delegate object PropertyGetInvoker(Control control, object noncontrol, string propertyName);
private delegate void PropertySetInvoker(Control control, object noncontrol, string propertyName, object value);
private static PropertyInfo GetPropertyInfo(Control control, object noncontrol, string propertyName) {
if (control != null && !string.IsNullOrEmpty(propertyName)) {
PropertyInfo pi = null;
Type t = null;
if (noncontrol != null) t = noncontrol.GetType();
else t = control.GetType();
pi = t.GetProperty(propertyName);
if (pi == null) throw new InvalidOperationException(string.Format("Can't find property {0} in {1}.", propertyName, t.ToString()));
return pi;
} else throw new ArgumentNullException("Invalid argument.");
}
public static object Invoke(Control control, string methodName, params object[] args) {
if (control != null && !string.IsNullOrEmpty(methodName))
if (control.InvokeRequired) return control.Invoke(new MethodInvoker(Invoke), control, methodName, args);
else {
MethodInfo mi = null;
if (args != null && args.Length > 0) {
Type[] types = new Type[args.Length];
for (int i = 0; i References
- Sergiu Josan, Making Controls Thread-safely, May 2009
- vicoB, Extension of safeInvoke, July 2010
The End. \(\Box\)
💈 A Cross-Thread Call Helper Class的更多相关文章
- update the UI property cross thread
this.Invoke((MethodInvoker)delegate { txtResult.Text = sbd.ToString(); // runs on UI thread });
- Flink - Checkpoint
Flink在流上最大的特点,就是引入全局snapshot, CheckpointCoordinator 做snapshot的核心组件为, CheckpointCoordinator /** * T ...
- [转]How to display the data read in DataReceived event handler of serialport
本文转自:https://stackoverflow.com/questions/11590945/how-to-display-the-data-read-in-datareceived-event ...
- c#子线程线程中操作窗体更新的报错
用 在执行上传时,由于操作较长窗体界面卡住,于是用task解决 Task t1 = new Task(manage.UploadData); t1.Start(); 结果不卡了,程序也传完了,运行到更 ...
- 进程创建过程详解 CreateProcess
转载请您注明出处:http://www.cnblogs.com/lsh123/p/7405796.html 0x01 CreateProcessW CreateProcess的使用有ANSI版本的Cr ...
- C#委托+回调详解
今天写不完,明天会接着写的,,,, 学习C#有一段时间了,不过C#的委托+回调才这两天才会用,以前只是知道怎么用.前面的一篇文章,函数指针,其实是为这个做铺垫的,说白了委托就相当于C语言中的函数指针, ...
- windows中的进程和线程
今天咱们就聊聊windows中的进程和线程 2016-09-30 在讨论windows下的进程和线程时,我们先回顾下通用操作系统的进程和线程.之所以称之为通用是因为一贯的本科或者其他教材都是这么说的: ...
- [MethodImpl(MethodImplOptions.Synchronized)]、lock(this)与lock(typeof(...))
对于稍微有点经验的.NET开发人员来说,倘若被问及如何保持线程同步,我想很多人都能说好好几种.在众多的线程同步的可选方式中,加锁无疑是最为常用的.如果仅仅是基于方法级别的线程同步,使用System.R ...
- Xamarin.Forms客户端第一版
Xamarin.Forms客户端第一版 作为TerminalMACS的一个子进程模块,目前完成第一版:读取展示手机基本信息.联系人信息.应用程序本地化. 功能简介 详细功能说明 关于TerminalM ...
- [源码解析] 深度学习流水线并行 PipeDream(5)--- 通信模块
[源码解析] 深度学习流水线并行 PipeDream(5)--- 通信模块 目录 [源码解析] 深度学习流水线并行 PipeDream(5)--- 通信模块 0x00 摘要 0x01 前言 0x02 ...
随机推荐
- hive导出查询文件到本地文件的2种办法
通过HQL语句 可以将hive 中表的数据生成到指定的目录. 有时候 我们可以利用hive来生成统计的中间文件(比源文件小的多的) 方法有如下2种: 1.INSERT OVERWRITE LOCAL ...
- JavaScript学习日志:关于js分号
javascript有自动添加分号的功能,但是不是所有情况都会自动添加,要区分: 1,如果语句独占一行 如果当前行内的语句能够被js正确解析,那么就会在句尾添加一个分号. (如何判断是否正确解析?你在 ...
- 记一些安卓app反编译修改的记录
2017-12-2209:00:40 好几天没有写过博客了,因为马上要期末考试,只能暂且放下我的小玩物,专心复习我的期末考试. 今天突然想设置一个安卓的栏目,记录下自己从高中就爱玩的一些东西,像刷机呀 ...
- JAVA中利用反射机制进行对象和Map相互转换的方法
JAVA的反射机制主要作用是用来访问对象的属性.方法等等.所以,JAVA中对象和Map相互转换可以利用JAVA的反射机制来实现.例子如下: 一.对象转Map的方法 public static Map& ...
- MS SQL 监控磁盘空间告警
这几天突然有个想法:希望能够自动监控.收集数据库服务器的磁盘容量信息,当达到一个阀值后,自动发送告警邮件给DBA,将数据库磁盘详细信息告知DBA,提醒DBA做好存储规划计划,初步的想法是通过作业调用存 ...
- 对datatable操作经验-排序和分页
1.datatable排序1: public DataTable SortDesc(DataTable dt){ DataView dv = new DataView(); dv.Table = dt ...
- 使用jdbc存储图片和大文本
package cn.itcast.i_batch; import java.sql.Connection; import java.sql.PreparedStatement; import jav ...
- chrome disable-web-security 关闭安全策略 解决跨域
Chrome 跨域访问线上接口 时间:2016-04-21 作者:zhongxia 前后端分离之后,联调的时候就会出现问题,那就是Ajax跨域问题. 跨域问题的解决方案有很多种比如常规的 后端使用CR ...
- C++——带默认参数值的函数
函数在声明时可以预先给出默认的形参值,调用时如给出实参,则采用实参值,否则采用预先给出的默认参数值. ,) { return x + y;} int main() { add(,);//10+20 a ...
- JAVA中的数据存储空间简述
在 JAVA 中,有六个不同的地方可以存储数据: 1. 寄存器( register ): 最快的存储区,因为它位于不同于其他存储区——处理器内部.但是寄存器的数量极其有限,所以寄存器由编译器根据需求进 ...