跨线程创建创建控件和刷新数据需要使用到委托,C#里面BeginInvoke属于是异步调用,Invoke属于是同步调用
示例包含跨线程实现跨线程访问lable数据和创建控件。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public delegate void update_lable(string str);
static update_lable update_lable_object;
public delegate bool add_controls();
static add_controls add_controls_object;
public Form1() {
InitializeComponent();
update_lable_object = new update_lable(update_lable_func);
Thread update_lable_thread = new Thread(update_lable_thread_func);
update_lable_thread.IsBackground = true;
update_lable_thread.Start();
add_controls_object = new add_controls(add_controls_func);
Thread add_control_thread = new Thread(add_control_thread_func);
add_control_thread.IsBackground = true;
add_control_thread.Start();
}
public void update_lable_thread_func() {
int count = 0;
while (count <= 6) {
try {
// 属于是同步调用
this.Invoke(update_lable_object, "test" + count );
Thread.Sleep(5000);
} catch (Exception e){
MessageBox.Show(e.Message);
}
finally {
this.Close(); // 退出程序
}
count++;
}
}
public void add_control_thread_func() {
try {
Thread.Sleep(5000);
// 属于是异步调用
this.BeginInvoke(add_controls_object);
} catch (Exception e) {
MessageBox.Show(e.Message);
}
finally {
this.Close();// 退出程序
}
}
public void update_lable_func(string str) {
label1.Text = str;
}
public bool add_controls_func() {
try {
Label lable = new Label();
lable.Top = 20;
lable.Left = 30;
lable.Size = new Size(80, 30);
lable.Text = "sdasdad";
Controls.Add(lable);
return true;
}catch(Exception e){
MessageBox.Show(e.Message);
return false;
}
}
}
}