1、通过Task开启线程
private void OpenThread()
{
Task task1 = new Task(() =>
{
this.DoSomethingLong("new Task(Action)");
Console.WriteLine($"通过new Task(Action)开启了一个线程,线程ID:{
Thread.CurrentThread.ManagedThreadId.ToString("00")}");
});
task1.Start();
Task task2 = Task.Run(() =>
{
this.DoSomethingLong("Task.Run(Action)");
Console.WriteLine($"通过Task.Run(Action)开启了一个线程,线程ID:{
Thread.CurrentThread.ManagedThreadId.ToString("00")}");
});
Func<int> func = () => {
return DateTime.Now.Year; };
Task<int> task3 = Task.Run(func);
int year = task3.Result;
Console.WriteLine($"有返回值的任务 今年是 {
year} 年");
TaskFactory taskFactory1 = new TaskFactory();
taskFactory1.StartNew(() =>
{
this.DoSomethingLong("new TaskFactory() taskFactory.StartNew(Action)");
Console.WriteLine($"通过new TaskFactory() 然后taskFactory.StartNew(Action)开启了一个线程,线程ID:{
Thread.CurrentThread.ManagedThreadId.ToString("00")}");
});
TaskFactory taskFactory2 = Task.Factory;
taskFactory2.StartNew(() =>
{
this.DoSomethingLong("Task.Factory taskFactory.StartNew");
Console.WriteLine($"通过Task.Factory 然后taskFactory.StartNew(Action)开启了一个线程,线程ID:{
Thread.CurrentThread.ManagedThreadId.ToString("00")}");
});
}

2、Task来源
private void TaskSource()
{
ThreadPool.SetMaxThreads(14, 14);
List<int> countlist = new List<int>();
List<Task> tasklist = new List<Task>();
for(int i = 0; i < 100; i++)
{
int k = i;
tasklist.Add(Task.Run(() =>
{
countlist.Add(Thread.CurrentThread.ManagedThreadId);
Console.WriteLine($"k={
k}, threadId = {
Thread.CurrentThread.ManagedThreadId.ToString("00")}");
}));
}
Task.WaitAll(tasklist.ToArray());
Console.WriteLine($"最大线程为:{
countlist.Distinct().Count()}");
}

3、父子线程场景A