#region Threads
private void btnThreads_Click (object sender, EventArgs e )
{
Console.WriteLine($"****************btnThreads_Click Start " +
$"{Thread.CurrentThread.ManagedThreadId.ToString("00" )} " +
$"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff" )} ***************" );
ThreadStart threadStart = () => this .DoSomethingLong("btnThreads_Click" );
Thread thread = new Thread(threadStart);
thread.Start();
Console.WriteLine($"****************btnThreads_Click End " +
$"{Thread.CurrentThread.ManagedThreadId.ToString("00" )} " +
$"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff" )} ***************" );
}
#endregion
thread.Join ();
thread.Join (500 );
while (thread.ThreadState != ThreadState.Stopped)
{
Thread.Sleep (100 );
}
Console.WriteLine (thread.IsBackground);
thread.IsBackground = true ;
thread.Priority = ThreadPriority.Highest;
ThreadPool线程池
ThreadPool用法
private void btnThreadPool_Click (object sender, EventArgs e)
{
Console.WriteLine ($"****************btnThreadPool_Click Start " +
$"{Thread.CurrentThread.ManagedThreadId.ToString(" 00 ")} " +
$"{DateTime.Now.ToString(" yyyy-MM-dd HH:mm:ss.fff")}***************" );
ThreadPool.QueueUserWorkItem (t => this.DoSomethingLong ("btnThreadPool_Click" ));
ThreadPool.SetMaxThreads (16 , 16 );
ThreadPool.SetMinThreads (8 , 8 );
{
ThreadPool.GetMaxThreads (out int workerThreads, out int completionPortThreads);
Console.WriteLine ($"workerThreads={workerThreads}
completionPortThreads={completionPortThreads}" );
}
{
ThreadPool.GetMinThreads (out int workerThreads, out int completionPortThreads);
}
Console.WriteLine ($"****************btnThreadPool_Click End " +
$"{Thread.CurrentThread.ManagedThreadId.ToString(" 00 ")} " +
$"{DateTime.Now.ToString(" yyyy-MM-dd HH:mm:ss.fff")}***************" );
}
ManualResetEvent manualResetEvent = new ManualResetEvent(false );
ThreadPool.QueueUserWorkItem(t =>
{
this .DoSomethingLong("btnThreadPool_Click" );
manualResetEvent.Set ();
});
manualResetEvent.WaitOne();
也有缺点,一般来说,不要阻塞线程池的线程
private void ThreadWithCallback (Action act, Action callback)
{
Thread thread = new Thread (() => {
act.Invoke ();
callback.Invoke ();
});
thread.Start ();
}
this.ThreadWithCallback (() =>
Console.WriteLine ($"这里是action
{Thread.CurrentThread.ManagedThreadId.ToString(" 00 ")}" )
, () =>
Console.WriteLine ($"这里是callback
{Thread.CurrentThread.ManagedThreadId.ToString(" 00 ")}" ));
private Func<T> ThreadWithReturn<T> (Func<T> func )
{
T t = default (T);
Thread thread = new Thread(()=>
{
t = func .Invoke();
});
thread.Start();
return () =>
{
thread.Join();
return t;
};
}
Func <int> func = this .ThreadWithReturn <int>(() =>
{
Thread .Sleep (2000 );
return DateTime .Now .Millisecond ;
});
Console .WriteLine ("12324546576586789789" );
int iResult = func.Invoke ();
Console .WriteLine (iResult);
#region Task
private void btnTask_Click (object sender, EventArgs e )
{
Console.WriteLine($"****************btnTask_Click Start " +
$"{Thread.CurrentThread.ManagedThreadId.ToString("00" )} " +
$"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff" )} ***************" );
Task.Run(() => this .DoSomethingLong("btnTask_Click1" ));
Task.Run(() => this .DoSomethingLong("btnTask_Click2" ));
TaskFactory taskFactory = Task.Factory;
taskFactory.StartNew(() => this .DoSomethingLong("btnTask_Click3" ));
new Task(() => this .DoSomethingLong("btnTask_Click4" )).Start();
Console.WriteLine($"****************btnTask_Click End " +
$"{Thread.CurrentThread.ManagedThreadId.ToString("00" )} " +
$"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff" )} ***************" );
}
#endregion
任务能并发进行:提升速度 优化体验
List <Task > taskList = new List <Task >();
Console .WriteLine ($"项目经理启动一个项目。。。【{Thread.CurrentThread.ManagedThreadId.ToString(" 00 ")}】" );
Console .WriteLine ($"前置准备工作。。。【{Thread.CurrentThread.ManagedThreadId.ToString(" 00 ")}】" );
Console .WriteLine ($"开始编程。。。【{Thread.CurrentThread.ManagedThreadId.ToString(" 00 ")}】" );
taskList.Add (Task .Run (() => this .Coding ("小张" , "Client" )));
taskList.Add (Task .Run (() => this .Coding ("小王" , "Portal" )));
taskList.Add (Task .Run (() => this .Coding ("小李" , "Service" )));
taskList.Add (Task .Run (() => this .Coding ("小陈" , "Jump" )));
taskList.Add (Task .Run (() => this .Coding ("小爱" , "Monitor" )));
Task .WaitAny (taskList.ToArray ());
Console .WriteLine ($"完成里程碑【{Thread.CurrentThread.ManagedThreadId.ToString(" 00 ")}】" );
Task .WaitAll (taskList.ToArray ());
Task .WaitAll (taskList.ToArray (), 1000 );
Console .WriteLine ("等待1s后,执行动作" );
Console .WriteLine ($"甲方验收。。。【{Thread.CurrentThread.ManagedThreadId.ToString(" 00 ")}】" );
private void Coding (string name, string project )
{
Console.WriteLine($"****************Coding {name} Start {project} {Thread.CurrentThread.ManagedThreadId.ToString("00" )} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff" )} ***************" );
long lResult = 0 ;
for (int i = 0 ; i < 1000000000 ; i++)
{
lResult += i;
}
Console.WriteLine($"****************Coding {name} End {project} {Thread.CurrentThread.ManagedThreadId.ToString("00" )} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff" )} {lResult} ***************" );
}
以上都会阻塞线程,下面的不阻塞:
TaskFactory taskFactory = new TaskFactory ();
taskFactory.ContinueWhenAll (taskList.ToArray (), tList =>
{
Console .WriteLine ($"部署环境,联调测试。。。【{Thread.CurrentThread.ManagedThreadId.ToString(" 00 ")}】" );
});
taskFactory.ContinueWhenAny (taskList.ToArray (), t =>
{
Console .WriteLine ($"部署环境,联调测试。。。【{Thread.CurrentThread.ManagedThreadId.ToString(" 00 ")}】" );
});
Task .WhenAny (taskList.ToArray ()).ContinueWith (t =>
{
Console .WriteLine ($"得意的笑。。。【{Thread.CurrentThread.ManagedThreadId.ToString(" 00 ")}】" );
});
Task .WhenAll (taskList.ToArray ()).ContinueWith (t =>
{
Console .WriteLine ($"部署环境,联调测试。。。【{Thread.CurrentThread.ManagedThreadId.ToString(" 00 ")}】" );
});
List <int > list = new List <int >();
for (int i = 0 ; i < 10000 ; i++)
{
list.Add(i);
}
Action<int > action = i =>
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString("00" ));
Thread.Sleep(new Random(i).Next(100 , 300 ));
};
List <Task> taskList = new List <Task>();
foreach (var item in list)
{
int k = item;
Task.Run(() => action.Invoke(k));
if (taskList.Count > 10 )
{
Task.WaitAny(taskList.ToArray());
taskList.Where(t => t.Status != TaskStatus.RanToCompletion).ToList();
}
}
Task.WhenAll(taskList.ToArray());
想知道线程是由哪个完成的
TaskFactory taskFactory = new TaskFactory ();
List <Task > taskList = new List <Task >();
taskList.Add (taskFactory.StartNew (o => this .Coding ("爱书客" , "Client" ), "爱书客" ));
taskList.Add (taskFactory.StartNew (o => this .Coding ("风动寂野" , "Portal" ), "风动寂野" ));
taskList.Add (taskFactory.StartNew (o => this .Coding ("笑看风云" , "Service" ), "笑看风云" ));
taskFactory.ContinueWhenAny (taskList.ToArray (), t =>
{
Console .WriteLine (t.AsyncState );
Console .WriteLine ($"部署环境,联调测试。。。【{Thread.CurrentThread.ManagedThreadId.ToString(" 00 ")}】" );
});
taskFactory.ContinueWhenAll (taskList.ToArray (), tList =>
{
Console .WriteLine (tList[0 ].AsyncState );
Console .WriteLine ($"部署环境,联调测试。。。【{Thread.CurrentThread.ManagedThreadId.ToString(" 00 ")}】" );
});
Task.Run(
() =>
{
Task.WaitAny(taskList.ToArray());
Console.WriteLine($"完成里程碑 【{Thread.CurrentThread.ManagedThreadId.ToString("00" )} 】" );
Task.WaitAll(taskList.ToArray());
Console.WriteLine($"告诉甲方验收,上线使用【{Thread.CurrentThread.ManagedThreadId.ToString("00" )} 】" );
});
{
Task.Delay(1000 );
Thread.Sleep(1000 );
Stopwatch stopwatch = new Stopwatch ();
stopwatch.Start();
Thread.Sleep(2000 );
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
}
{
Stopwatch stopwatch = new Stopwatch ();
stopwatch.Start();
Task.Delay(2000 ).ContinueWith(t =>
{
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
});
}
{
Stopwatch stopwatch = new Stopwatch ();
stopwatch.Start();
Task.Run(() =>
{
Thread.Sleep(2000 );
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
});
}
#region Parallel
private void btnParallel_Click (object sender, EventArgs e )
{
Console.WriteLine($"****************btnParallel_Click Start " +
$"{Thread.CurrentThread.ManagedThreadId.ToString("00" )} " +
$"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff" )} ***************" );
Console.WriteLine($"****************btnParallel_Click End " +
$"{Thread.CurrentThread.ManagedThreadId.ToString("00" )} " +
$"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff" )} ***************" );
}
#endregion
parallelOptions 可以控制并发数量:
ParallelOptions parallelOptions = new ParallelOptions ();
parallelOptions.MaxDegreeOfParallelism = 3 ;
Parallel .For (0 , 10 , parallelOptions, i => this .Coding ("爱书客" , "Client" + i));
Task .Run (() =>
{
ParallelOptions parallelOptions = new ParallelOptions ();
parallelOptions.MaxDegreeOfParallelism = 3 ;
Parallel .For (0 , 10 , parallelOptions, i => this .Coding ("爱书客" , "Client" + i));
});
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏