接上篇C# 總結ManualResetEvent與AutoResetEvent
C# 總結ManualResetEvent與AutoResetEvent
public class TestAutoResetEvent
{
Thread thin;
Thread thout;
Queue<int> enqueen = new Queue<int>();
AutoResetEvent ar = new AutoResetEvent(false);
public TestAutoResetEvent()
{
thin = new Thread(AddToenque);
thin.Name = "thin";
thin.Start();
thout = new Thread(OutEnque);
thout.Name = "thout";
thout.Start();
}
public void AddToenque()
{
int k = 0;
while (true)
{
for (int i = 1; i < 2; i++)
{
if (k > 10)
{
break;
}
enqueen.Enqueue(i);
Console.WriteLine("入隊___" + i);
Thread.Sleep(500);
k++;
}
ar.Set();
}
}
public void OutEnque()
{
while (true)
{
ar.WaitOne();
if (enqueen.Count() > 0)
{
for (int i = 0; i < enqueen.Count(); i++)
{
Console.WriteLine("出隊:__" + enqueen.Dequeue());
Thread.Sleep(500);
//ar.Reset();
}
}
}
}
}
public class ProductAndCostTester
{
Thread threadproductglue;
Thread threadproductassblem;
Thread threadCost;
List<int> _goodList = new List<int>();
private ManualResetEvent _mre = new ManualResetEvent(false);
public ProductAndCostTester()
{
_goodList = new List<int>();
_mre = new ManualResetEvent(false);//false初始化狀態爲無信號,將使WaitOne阻塞
threadproductglue = new Thread(ProductGlue);
threadproductglue.Name = "ProductGlue";
threadproductglue.Start();
threadproductassblem = new Thread(ProductAssblem);
threadproductassblem.Name = "ProductAssblem";
threadproductassblem.Start();
threadCost = new Thread(Cost);
threadCost.Name = "Cost";
threadCost.Start();
}
public void ProductGlue()
{
while (true)
{
for (int i = 0; i < 5; i++)
{
_goodList.Add(1);
}
_mre.Set();
Thread.Sleep(5000);
}
}
public void ProductAssblem()
{
while (true)
{
for (int i = 0; i < 8; i++)
{
_goodList.Add(1);
}
_mre.Set();
Thread.Sleep(8000);
}
}
public void Cost()
{
while (true)
{
if (_goodList.Count() > 0)
{
Console.WriteLine("Cost " + _goodList.Count + " at " + DateTime.Now.ToString("HH:mm:ss"));
_goodList.Clear();
_mre.Reset();
}
else
{
Console.WriteLine("No cost at " + DateTime.Now.ToString("HH:mm:ss"));
_mre.WaitOne();//如果沒有可消費的產品,即無信號,則會阻塞
}
}
}
}
public class TestAuto
{
public TestAuto()
{
}
AutoResetEvent autoResetEvent = new AutoResetEvent(false); //false代表默認中阻塞狀態
void Do()
{
var worker = new Thread(() =>
{
Console.WriteLine("Start worker");
Console.WriteLine("wait");
autoResetEvent.WaitOne(); //等待信號
Console.WriteLine("do");
});
worker.Start();
}
void Signal()
{
Console.WriteLine("Sent signal");
Console.ReadKey();
autoResetEvent.Set(); //發送信號
Console.ReadKey();
}
}