用 Thread实现多线程:
// 1 不带传入参数的
public void ThreadFun()
{
// 处理后台,例如等待网络响应或耗时长的计算任务
Console.WriteLine("Thrad:start do something");
Thread.Sleep(2000);
Console.WriteLine("Thrad:end ");
}
public void MainFun()
{
Thread thread = new Thread(ThreadFun);
thread.Start();
// 这时主线程还可以做其它事,例如响应用户的取消操作
Console.WriteLine("Main:Need to wait");
}
// 2 使用带参数的
private void ThreadFun2(object o)
{
string name = o as string; //类型转换
Console.WriteLine(name + ":Thrad:start do something");
Thread.Sleep(2000);
Console.WriteLine(name + ":Thrad:end ");
}
public void MainFun2()
{
Thread thread = new Thread(ThreadFun2);
thread.Start("Mark");
// 这时主线程还可以做其它事,例如响应用户的取消操作
Console.WriteLine("Main:Need to wait");
}
// 3 使用匿名方法
public void MainFun3()
{
Thread thread = new Thread(() => {
Console.WriteLine("Thrad:start do something");
Thread.Sleep(2000);
Console.WriteLine("Thrad:end ");
});
thread.Start();
// 这时主线程还可以做其它事,例如响应用户的取消操作
Console.WriteLine("Main:Need to wait");
}
使用Task 实现多线程
// 4 Task
public void MainFun4()
{
// 1)
string name = "Mark";
Task task = new Task(() => {
Console.WriteLine(name + " Task:start do something");
Thread.Sleep(2000);
Console.WriteLine(name + " Task:end ");
});
task.Start();
// 2)
Task.Run(() =>
{
Console.WriteLine(name + " Task:start do something");
Thread.Sleep(2000);
Console.WriteLine(name + " Task:end ");
});
// 这时主线程还可以做其它事,例如响应用户的取消操作
Console.WriteLine("Main:Need to wait");
}
// 5 Task
public void MainFun5()
{
Task[] taskList = new Task[2];
string name = "Mark";
taskList[0] = Task.Run(() => {
Console.WriteLine(name+ " Task:start do something");
Thread.Sleep(2000);
Console.WriteLine(name + " Task:end ");
});
taskList[1] = Task.Run(() => {
Console.WriteLine(name + " Task:start do something");
Thread.Sleep(5000);
Console.WriteLine(name + " Task:end ");
});
// 等待多个子线程完成后再继续:
Task.WaitAll(taskList);
}
//async/await的实现:
public void MainFun6()
{
var ret1 = AsyncGetsum();
Console.WriteLine("主线程执行其他处理");
for (int i = 1; i <= 3; i++)
Console.WriteLine("Call Main()");
int result = ret1.Result; //阻塞主线程
Console.WriteLine("任务执行结果:{0}", result);
}
async Task<int> AsyncGetsum()
{
await Task.Delay(1);
int sum = 0;
Console.WriteLine("使用Task执行异步操作.");
for (int i = 0; i < 100; i++)
{
sum += i;
}
return sum;
}
|