0%

多线程并行调用同一个方法

多线程调用同一个方法,并行执行,提高程序响应速度;

完整代码

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);
//maxWorkerThreads,64位操作系统是2047,32位是 1023,因为自己占用一个线程;maxIoThreads 都是1000;
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) // 始终控制线程数在 <= 100 个Task任务执行;
{
var task = await Task.WhenAny(list.ToArray());//任意一个完成,返回task的索引;
list.Remove(task);
}

}

Console.WriteLine("ok");

await Task.WhenAll(list.ToArray());

Console.WriteLine(currentDictionary.Count);
Console.WriteLine("end");
}



/// <summary>
/// 多线程执行
/// </summary>
static async Task show()
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + " " + Thread.CurrentThread.ManagedThreadId);
//Thread.Sleep(1000 * 60);
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 是当前程序,获取服务器最大线程池;利于提高线程创建速度;

执行结果

image-20220719151915659

-------------本文结束感谢您的阅读-------------
本网站所有内容均收集于互联网或自己创作, 方便于网友与自己学习交流,如有侵权,请留言,立即处理

欢迎关注我的其它发布渠道

本文标题:多线程并行调用同一个方法

文章作者:peter

发布时间:2022年07月19日 - 14:07

最后更新:2022年07月28日 - 11:07

原始链接:https://www.123zhibei.xyz/article/944bc9e9.html

许可协议: 转载请保留原文链接及作者。