多线程调用同一个方法,并行执行,提高程序响应速度;
完整代码
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 55 56 57 58 59 60 61
| static ConcurrentDictionary<string, string> currentDictionary = new System.Collections.Concurrent.ConcurrentDictionary<string, string>();
static void Main(string[] args) { Task.Run(() => testMutiThread()).Wait(); }
private static async Task testMutiThread() { #region 开启这段代码; 原来本程序6分钟执行完毕, 加上后1分钟执行完毕; int maxWorkerThreads, maxIoThreads; ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxIoThreads);
Console.WriteLine("maxWorkerThreads = " + maxWorkerThreads); Console.WriteLine("maxIoThreads = " + maxIoThreads); var res = ThreadPool.SetMinThreads(maxWorkerThreads, maxIoThreads); Console.WriteLine(res); #endregion
var list = new List<Task>();
for (int i = 0; i < 10000; i++) {
list.Add(await Task.Factory.StartNew(async () => await show()));
if (list.Count == 100) { var task = await Task.WhenAny(list.ToArray()); list.Remove(task); }
}
Console.WriteLine("ok");
await Task.WhenAll(list.ToArray());
Console.WriteLine(currentDictionary.Count); Console.WriteLine("end"); }
static async Task show() { Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + " " + Thread.CurrentThread.ManagedThreadId); await Task.Delay(1000 * 5);
currentDictionary.TryAdd(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
Console.WriteLine($"-当前进程所有线程数:{Process.GetCurrentProcess().Threads.Count} ---"); Console.WriteLine(); }
|
多线程异步调用同一个异步方法 show;
多线程对currentBag包,添加随机字符串 guid值,预计10000个,实际添加就是 10000个;
SetMinThreads 是当前程序,获取服务器最大线程池;利于提高线程创建速度;
执行结果