1.有参无返回
2.等到所有线程都执行完毕后,再执行主线程
class Program
{
static List<ManualResetEvent> manualResetEvents = new List<ManualResetEvent>();
static void Main(string[] args)
{
try
{
ThreadPool.SetMinThreads(3, 3);
for (int i = 0; i < 10; i++)
{
Tesla tesla = new Tesla();
tesla.mre = new ManualResetEvent(false);
tesla.Model_S = "Model S " + i;
tesla.Model_3 = i;
tesla.Model_X = DateTime.Now;
if (i / 2 == 0)
{
tesla.Model_Y = true;
}
else
{
tesla.Model_Y = false;
}
manualResetEvents.Add(tesla.mre);// 这一步重要 一定需要将参数对象添加到List中,当方法执行完成的时候会修改为true
ThreadPool.QueueUserWorkItem(BiliBili, tesla);// 将方法排入多线程队列,线程可用时执行
}
WaitHandle.WaitAll(manualResetEvents.ToArray());// 最多支持64线程
Console.WriteLine("结束了");
}
catch (Exception e)
{
Console.WriteLine("Error:" + e.Message);
}
finally
{
Console.ReadKey();
}
}
static void BiliBili(object obj)
{
Tesla tesla = obj as Tesla;
Console.WriteLine(tesla.Model_3 + " return:Model_S=" + tesla.Model_S + " Model_3=Model 3 " + tesla.Model_3 + " Model_X=" + tesla.Model_X + " Model_Y=" + tesla.Model_Y + " | 线程ID:" + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(2500);
if (tesla.Model_3 / 2 == 0)
{
Thread.Sleep(5000);
//int d = 10 / tesla.Model_3;
}
tesla.mre.Set();//发送信号量 本线程执行完毕 / 重要
}
}
public class Tesla
{
public ManualResetEvent mre;
public string Model_S { get; set; }
public int Model_3 { get; set; }
public DateTime Model_X { get; set; }
public bool Model_Y { get; set; }
}