C#中创建线程的几种方法
1. Task
private void button1_Click(object sender, EventArgs e)
{
//方式1
Task.Factory.StartNew(()=>Test());
//方式2
Task task2 = new Task(()=>{
Test();
});
task2.Start();
//方式3
Task.Run(()=>{
Test();
});
}
private void Test()
{
// do something
}
2. new Thread()
private void button1_Click(object sender, EventArgs e)
{
//方式1:
Thread TestThread = new Thread(Test);
TestThread.IsBackground = true;
TestThread.Start();
//方式2:
Thread thread2 = new Thread(new ThreadStart(Test))
{
IsBackground = true
};
thread2.Start();
}
private void Test()
{
// do something
}
异步委托线程中控件访问
private void button1_Click(object sender, EventArgs e)
{
Task.Run(()=>{
Test1(); //方式1
ShowTime();//方式2
SetLabelText(lable3, "hello");//方式3
});
}
//方式1
private void Test1()
{
// 方法1
this.BeginInvoke((MethodInvoker)delegate
{
label1.Text = "hello";
});
//方法2
this.Invoke(new EventHandler(delegate
{
label1.Text = "Hello";
}));
}
//方式2
private void ShowTime()
{
if(label2.InvokerRequired)//判断当前线程是否和控件所属线程为同一线程
{
label2.Invoke(new Action(ShowTime)); //不为同一线程,则使用委托执行该方法本身
}
else
{
label2.Text = DateTime.Now.ToLongTimeString(); //为同一线程则直接刷新label1
}
}
//方式3
delegate void setLabelTextCallback(Label label, string text);
public void SetLabelText(Label label, string text)
{
if(label.InvokeRequired)
{
while(!label.IsHandleCreated)
{
if (label.Disposing || label.IsDisposed)
return;
}
setLabelTextCallback callback = new setLabelTextCallback(SetLabelText);
label.Invoke(callback, new object[] { label, text });
}
else
{
label.Text = text;
}
}