using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
//信号量Semaphore限制可同时访问某一资源或资源池的线程数。指示控制的资源初始和最大线程并发数为2
static Semaphore sema = new Semaphore(1, 1);
static int aliveCount = 0;
static object obj = new object();
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
var thread = new Thread(Test) { Name = $"Thread{i}" };
thread.Start();
}
var timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.Elapsed += MTMShareCountry;
timer.Enabled = true;
timer.AutoReset = true;
timer.Start();
Console.ReadKey();
}
private static void
C# 多线程使用信号量控制处理效率,统计活动中的线程
最新推荐文章于 2024-08-13 13:10:22 发布
本文详细介绍了如何在C#中利用信号量(Semaphore)进行多线程控制,以优化资源利用并提升程序执行效率。通过实例代码展示了如何统计并管理活动线程,确保并发安全。
摘要由CSDN通过智能技术生成