C#Threads Handling事件

时间:2012-10-07 06:06:12

标签: c# multithreading events event-handling

我正在尝试让线程也处理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);
}

1 个答案:

答案 0 :(得分:0)

不幸的是,事件并不像那样。处理程序总是由引发事件的线程执行,而不是订阅事件的线程。