C# winform编程中多线程操作控件方法

 private void Form1_Load(object sender, EventArgs e)
{
Thread newthread = new Thread(new ThreadStart(BackgroundProcess));
newthread.Start(); } /// <summary>
/// 定义一个代理
/// </summary>
private delegate void CrossThreadOperationControl(); private void BackgroundProcess()
{
// 将代理实例化为一个匿名代理
CrossThreadOperationControl CrossDelete = delegate()
{
int i = ;
while (i < )
{
// 向列表框增加一个项目
listBox1.Items.Add("Item " + i.ToString());
i++;
}
label1.Text = "我在新线程里访问这个lable!";
listBox1.Items.Add(label1.Text);
};
listBox1.Invoke(CrossDelete);
}

收集一下,在C# winform编程中多线程操作控件时,可以有下面种方法:

1. 又看到一种方法(2014.1.6):

1. 刚看到一种方法(2014.1.5):

 private void btnTest_Click(object sender, EventArgs e)
{
if (this.txtIP.Text.Trim() != "" && this.txtPort.Text.Trim() != "")
{
string proxy = this.txtIP.Text.Trim() + ":" + this.txtPort.Text.Trim();
string result = string.Empty;
this.btnTest.Enabled = false;
new Thread(delegate
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
HttpClient httpClient = new HttpClient();
httpClient.Proxy = new WebProxy(proxy);
httpClient.TimeOut = ;
object result;
try
{
string a = httpClient.Get("http://www.baidu.com", "", "", "", "", "get");
if (a != "")
{
result = "响应成功!";
}
else
{
result = "响应失败!";
}
}
catch
{
}
stopwatch.Stop();
result = result;
result = string.Concat(new object[]
{
result,
",响应花费:",
stopwatch.ElapsedMilliseconds,
"ms"
});
this.BeginInvoke(delegate
{
this.lbResult.Text = result;
this.btnTest.Enabled = true;
});
})
{
IsBackground = true
}.Start();
}
else
{
this.lbResult.Text = "请输入完整再提交!";
}
}

1. 直接使用表达式和Action()

 private void btnInitEnv_Click(object sender, EventArgs e)
{
//初始化环境时回显出来的文字不让看
try
{
this.textBoxOutPut.Clear();
this.btnInitEnv.Enabled = false;
this.labelStateInfo.Text = "";
this.labelStateInfo.ForeColor = Color.Red; if (!WriteToSerialPort("diags"))
{
this.btnInitEnv.Enabled = true;
return;
} Thread thread = new Thread(new ThreadStart(() =>
{
int i = ;
bool flagFind = false;
StringBuilder sb = new StringBuilder(); while (true)
{
Thread.Sleep();
this.Invoke(new Action(() =>
{
sb.Append(this.textBoxOutPut.Text);
this.textBoxOutPut.Clear();
if (sb.ToString().Contains("Entering recovery mode, starting command prompt"))
{
this.textBoxOutPut.AppendText(string.Format(PubilcConstVar.TerimalStrFormat,
DateTime.Now.ToString(PubilcConstVar.TimeFormat),
"Entering recovery mode, starting command prompt, Stop.\r\n"));
this.labelStateInfo.ForeColor = Color.Red;
this.labelStateInfo.Text = "初始化失败,请手动输入命令初始化";
flagFind = true;
this.btnInitEnv.Enabled = true;
}
else if (sb.ToString().Contains(":-)"))
{
this.textBoxOutPut.AppendText(string.Format(PubilcConstVar.TerimalStrFormat,
DateTime.Now.ToString(PubilcConstVar.TimeFormat),
"进入操作模式成功\r\n"));
this.labelStateInfo.ForeColor = Color.Blue;
this.labelStateInfo.Text = "初始化成功";
flagFind = true; //将业务按钮使能
EnableBussinessButtons();
}
})); if (flagFind || ++i > ) //找开标志或10秒超时中断
{
break;
}
} if (!flagFind)
{
this.Invoke(new Action(() =>
{
this.textBoxOutPut.Clear();
this.labelStateInfo.ForeColor = Color.Red;
this.labelStateInfo.Text = "初始化失败,超时";
this.btnInitEnv.Enabled = true; DisableBussinessButtons();
}));
}
})); thread.IsBackground = true;
thread.Start();
}
catch (Exception ex)
{
this.log.Write(ex.ToString());
}
}

2. 使用线程函数加action()

 private void btnInitEnv_Click(object sender, EventArgs e)
{
//初始化环境时回显出来的文字不让看
try
{
this.textBoxOutPut.Clear();
this.btnInitEnv.Enabled = false;
this.labelStateInfo.Text = "";
this.labelStateInfo.ForeColor = Color.Red; if (!WriteToSerialPort("diags"))
{
this.btnInitEnv.Enabled = true;
return;
} Thread thread = new Thread(new ThreadStart(MonitorOutPutThread)); thread.IsBackground = true;
thread.Start();
}
catch (Exception ex)
{
this.log.Write(ex.ToString());
}
}

线程函数:

 private void MonitorOutPutThread()
{
int i = ;
bool flagFind = false;
StringBuilder sb = new StringBuilder(); while (true)
{
Thread.Sleep();
this.Invoke(new Action(() =>
{
sb.Append(this.textBoxOutPut.Text);
this.textBoxOutPut.Clear();
if (sb.ToString().Contains("Entering recovery mode, starting command prompt"))
{
this.textBoxOutPut.AppendText(string.Format(PubilcConstVar.TerimalStrFormat,
DateTime.Now.ToString(PubilcConstVar.TimeFormat),
"Entering recovery mode, starting command prompt, Stop.\r\n"));
this.labelStateInfo.ForeColor = Color.Red;
this.labelStateInfo.Text = "初始化失败,请手动输入命令初始化";
flagFind = true;
this.btnInitEnv.Enabled = true;
}
else if (sb.ToString().Contains(":-)"))
{
this.textBoxOutPut.AppendText(string.Format(PubilcConstVar.TerimalStrFormat,
DateTime.Now.ToString(PubilcConstVar.TimeFormat),
"进入操作模式成功\r\n"));
this.labelStateInfo.ForeColor = Color.Blue;
this.labelStateInfo.Text = "初始化成功";
flagFind = true; //将业务按钮使能
EnableBussinessButtons();
}
})); if (flagFind || ++i > ) //找开标志或10秒超时中断
{
break;
}
} if (!flagFind)
{
this.Invoke(new Action(() =>
{
this.textBoxOutPut.Clear();
this.labelStateInfo.ForeColor = Color.Red;
this.labelStateInfo.Text = "初始化失败,超时";
this.btnInitEnv.Enabled = true; DisableBussinessButtons();
}));
}
}

3. 就是使用委托,这个网上例子很多,不再实现

上一篇:JavaScript来实现打开链接页面(转载)


下一篇:aptana studio 3 自动换行(无需插件)