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
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
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
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
异步委托线程中控件访问
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;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54