线程读写控件需要用委托(delegate)与Invoke/BeginInvoke来进行

参考内容:http://www.cnblogs.com/runner/archive/2011/12/30/2307576.html

1. 获取TextBox中的值

代码一:

 1         public delegate string GetTextBoxCallBack();
 2         private string GetInputText()
 3         {
 4             try
 5             {
 6                 if (this.txtInput.InvokeRequired)
 7                 {
 8                     GetTextBoxCallBack gtb = new GetTextBoxCallBack(GetInputText);
 9                     IAsyncResult ia = txtInput.BeginInvoke(gtb);
10                     return (string)txtInput.EndInvoke(ia);  //这里需要利用EndInvoke来获取返回值
11                 }
12                 else
13                 {
14                     return txtInput.Text;
15                 }
16             }
17             catch (Exception ex)
18             {
19                 return "";
20             }
21         }

 代码二:

 1         private string GetTextCallBack()
 2         {
 3             if (this.txtInput.InvokeRequired)
 4             {
 5                 string inputTxt = string.Empty;
 6                 this.txtInput.Invoke(new MethodInvoker(delegate { inputTxt = txtInput.Text; }));
 7                 return inputTxt;
 8             }
 9             else
10             {
11                 return this.txtInput.Text;
12             }
13         }

 

2.线程设置TextBox值

代码一:

 1         delegate void SetTextBoxCallback(string text);
 2         private void SetInputText(string text)
 3         {
 4             if (this.txtInput.InvokeRequired)
 5             {
 6                 SetTextBoxCallback d = new SetTextBoxCallback(SetInputText);
 7                 this.Invoke(d, new object[] { text });
 8             }
 9             else
10             {
11                 this.txtInput.Text = text;
12             }
13         }

 代码二:

1 string changeTxt = "Change Text";
2 txtInput.Invoke(new Action<String>(p =>
3                 {
4                     txtInput.Text = changeTxt;
5                 }), txtInput.Text);

 

posted on 2018-12-13 09:29  lazyneal  阅读(7441)  评论(0编辑  收藏  举报