我试图让线程也处理 pricecutEvent,但我无法让线程订阅 priceCutEvent。所以它不是由每个线程处理的。我这样做的原因是当 priceCutEvent 发生时,线程应该“购买”更多的鸡。但它只是由常规的“chickenStore”处理,而不是由 5 个线程处理。我该如何做到这一点,以便线程实际处理事件?我试过了:
ChickenFarm.priceCut += new priceCutEvent(reatilers[i].chickenOnSale);
但这不起作用。为你删除了很多。
public delegate void priceCutEvent(Int32 pr); //define a delegate
public delegate void orderEvent();
public static void changePrice(Int32 price)
{
if (price < chickenPrice) //a price cut occured
{
if (priceCut != null) //there is at least one subscriber
priceCut(price); //emit event to subscriber
}
chickenPrice = price;
}
public class myApplication
{
static void Main(string[] args)
{
ChickenFarm chicken = new ChickenFarm();
multiCellBuffer thisBuffer = new multiCellBuffer();
/*Alternatively we could use this instead of a regular expression:
ThreadStart starter = delegate{chicken.farmerFunc(thisBuffer);};
Thread farmer = new Thread(starter);
farmer.start(); */
Thread farmer = new Thread(() => chicken.farmerFunc(thisBuffer));
farmer.Start(); // Start one farmer thread
Retailer chickenstore = new Retailer();
Retailer.orderInNeedOfProcessing += new orderEvent(chicken.processOrder);
Thread[] retailers = new Thread[5];
ChickenFarm.priceCut += new priceCutEvent(chickenstore.chickenOnSale);
for (int i = 0; i < 5; i++) // Start N retailer threads
{
//Thread thread = new Thread(() => ReadCentralOutQueue("test"));
retailers[i] = new Thread(() => chickenstore.retailerFunc(thisBuffer, chicken));
retailers[i].Name = (i + 1).ToString();
retailers[i].Start();
}
}
}
public void chickenOnSale(Int32 p) // Event handler
{
// order chickens from chicken farm - send order into queue
OrderObject myOrder = new OrderObject();
myOrder.setID(Thread.CurrentThread.Name);
Console.WriteLine("Order ID: {0}", Thread.CurrentThread.Name);
Int64 myRandomCardNo = rng.Next(1000000000);
Int32 myRandomAmount = rng.Next(0, 100);
myOrder.setCardNo(myRandomCardNo);
myOrder.setAmount(myRandomAmount);
String myOrderString = encoder(myOrder);
Console.WriteLine("Un-Encrypted Order: {0}", myOrder.toString());
Console.WriteLine("Encrypted Order: {0}", myOrderString);
sendOrder(myBuffer, myOrderString);
Console.WriteLine("Store {0} chickens are on sale: as low as ${1} each",
Thread.CurrentThread.Name, p);
}