.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 
View Code

关键

  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 
View Code
原创粉丝点击