private static List<AutoResetEvent> autoResetEvents = new List<AutoResetEvent>();
private static int num = 0;
/// <summary>
///
/// </summary>
/// <param name="taskCount">任务数</param>
/// <param name="numCount">每个任务打印的数字个数</param>
static void WriteNum(int taskCount,int numCount)
{
for (int i = 0; i < taskCount; i++)
{
autoResetEvents.Add(new AutoResetEvent(false));
int setEventIndex = i + 1;
if (i == (taskCount - 1))
{
setEventIndex = 0;
}
int[] taskParams = { i, setEventIndex };
Task task = Task.Factory.StartNew((obj) => {
var set = (int[])obj;
for (int j = 0; j < numCount; j++)
{
autoResetEvents[set[0]].WaitOne();
num++;
Console.WriteLine($"线程ID:{Task.CurrentId},值:{num}");
autoResetEvents[set[1]].Set();
Thread.Sleep(100);
}
}, taskParams);
}
autoResetEvents[0].Set();
}