.NET并行计算和并发3-Invoke_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > .NET并行计算和并发3-Invoke

.NET并行计算和并发3-Invoke

 2017/8/18 12:31:34  kiss88  程序员俱乐部  我要评论(0)
  • 摘要:Control.Invoke方法(Delegate)在拥有此控件的基础窗口句柄的线程上执行指定的委托。Invoke方法搜索沿控件的父级链,直到它找到的控件或窗口具有一个窗口句柄;如果尚不存在当前控件的基础窗口句柄,或者找不到任何合适的句柄,Invoke方法将会引发异常。例子1publicclassMyFormControl:Form2{3publicdelegatevoidAddListItem();45publicAddListItemmyDelegate
  • 标签:.net 并行计算 net

Control.Invoke 方法 (Delegate)

在拥有此控件的基础窗口句柄的线程上执行指定的委托。

Invoke方法搜索沿控件的父级链,直到它找到的控件或窗口具有一个窗口句柄;

如果尚不存在当前控件的基础窗口句柄,或者找不到任何合适的句柄,Invoke方法

将会引发异常

例子

class="code_img_closed" alt="" src="/Upload/Images/2017081812/0015B68B3C38AA5B.gif">
  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 
logs_code_collapse">View Code

关键

  1         private void ThreadFunctionWrong()
  2         {
  3             //if direct call myDelegate(), it would throw an exception
  4             myDelegate();
  5         }
  6 
  7         private void ThreadFunctionRight()
  8         {
  9             //right way: must run at thead that creates myListBox control. 
 10             // Execute the specified delegate on the thread that owns
 11             // 'myListBox' control's underlying window handle.            
 12             this.Invoke(this.myDelegate);
 13         }

发表评论
用户名: 匿名