public class TaskPrint
{
List<AutoResetEvent> autoResetEvents = new List<AutoResetEvent>();
int num = 0;
//任务个数,打印数的个数
public 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();
}
}, taskParams);
}
autoResetEvents[0].Set();
}
}
class Program
{
static void Main(string[] args)
{
TaskPrint print = new TaskPrint();
print.WriteNum(2,50);
Console.ReadKey();
}
}