.NET并行计算和并发3-Invoke
来源:互联网 发布:soundhound mac 编辑:程序博客网 时间:2024/05/18 03:28
Control.Invoke 方法 (Delegate)
在拥有此控件的基础窗口句柄的线程上执行指定的委托。
Invoke方法搜索沿控件的父级链,直到它找到的控件或窗口具有一个窗口句柄;
如果尚不存在当前控件的基础窗口句柄,或者找不到任何合适的句柄,Invoke方法
将会引发异常。
例子
1 public class MyFormControl : Form 2 { 3 public delegate void AddListItem(); 4 5 public AddListItem myDelegate; 6 private Thread myThread; 7 private ListBox myListBox; 8 9 public MyFormControl() 10 { 11 var myButton = new Button(); 12 myListBox = new ListBox(); 13 myButton.Location = new Point(72, 160); 14 myButton.Size = new Size(152, 32); 15 myButton.TabIndex = 1; 16 myButton.Text = "Add items in list box"; 17 myButton.Click += new EventHandler(Button_Click); 18 myListBox.Location = new Point(48, 32); 19 myListBox.Name = "myListBox"; 20 myListBox.Size = new Size(200, 95); 21 myListBox.TabIndex = 2; 22 ClientSize = new Size(292, 273); 23 Controls.AddRange(new Control[] { myListBox, myButton }); 24 Text = " 'Control_Invoke' example"; 25 myDelegate = new AddListItem(AddListItemMethod); 26 } 27 28 public void AddListItemMethod() 29 { 30 String myItem; 31 for (int i = 1; i < 6; i++) 32 { 33 myItem = "MyListItem" + i.ToString(); 34 myListBox.Items.Add(myItem); 35 myListBox.Update(); 36 Thread.Sleep(3000); 37 } 38 } 39 40 private void Button_Click(object sender, EventArgs e) 41 { 42 myThread = new Thread(new ThreadStart(ThreadFunctionRight)); 43 myThread.Start(); 44 } 45 } 46
关键
1 private void ThreadFunctionWrong() 2 { 3 //if direct call myDelegate(), it would throw an exception 4 //because control resources are not created at this new thread 5 //so this thead cannot access these resources. 6 myDelegate(); 7 8 //other calculation at new thread 9 long j = 0; 10 for (long i = 0; i < 1e9; i++) 11 j++; 12 } 13 14 private void ThreadFunctionRight() 15 { 16 //right way: must run at thead that creates myListBox control. 17 // Execute the specified delegate on the thread that owns 18 // 'myListBox' control's underlying window handle. 19 //this is done in original thread 20 this.Invoke(this.myDelegate); 21 22 //other calculation at new thread 23 long j = 0; 24 for (long i = 0; i < 1e9; i++) 25 j++; 26 } 27
阅读全文
1 0
- .NET并行计算和并发3-Invoke
- .NET并行计算和并发3.2-多线程调用Invoke
- !.NET 4.0并行计算深入解读(FOR,FOREACH,Invoke)
- 并行计算&并发计算
- 并发计算 VS 并行计算
- 并行计算--并发构造纵览
- 并行和并发
- 并行和并发
- 并行和并发
- 理解并行和并发
- 并发和并行
- 并发和并行
- 并发和并行
- 并发和并行
- 并发和并行
- 并发和并行
- 并发和并行浅谈
- 并发和并行
- 一个项目的工作流程
- 275. To xor or not to xor(高斯消元求最大亦或值)
- exit(0)与exit(1)、return区别
- Award BIOS,AWI BIOS,Phoenix BIOS,兼容BIOS的部分警报的含义
- Eclipse hibernate Tools下载
- .NET并行计算和并发3-Invoke
- 攻击容器集群管理平台
- [leetcode]142. Linked List Cycle II@Java解题报告
- MFC学习笔记01-(_T()与L的区别)
- 软件测试过程中有哪些风险?
- 单链表的快排实现
- 《并发编程》--5.线程等待结束(join)和线程谦让(yield)
- String-引用计数的写时拷贝
- Python爬取表格及图片