代码之家  ›  专栏  ›  技术社区  ›  yoav.str

如何处理线程队列c#

  •  1
  • yoav.str  · 技术社区  · 14 年前

    你好 我想建立一个简单的程序

      Parallel.ForEach(m_CustomerArr, customer =>
            {
                customer.OrderSomthing();
            });
    

    当客户订购商品时,他会查询数据库,当商品用完时,他会联系供应商

          public bool takeOrder(Order o)
        {
                lock (s_QueueLocker)
                {
                    OrderQueue.Enqueue(o);
                }
                //waits here to be signaled by the working thread of supplier 
                o.m_ManualResetEvent.WaitOne();**
            return true;
        }  
    

    只有一个拥有supplierthread的队列的供应商:

       public void CreateThead()
        {
            Order currentOrder;
            while (true)
            {
                if (OrderQueue.Count != 0)
                {
                    currentOrder = OrderQueue.Dequeue();
                    DoOrder(currentOrder); 
                }
            }
    
        }
         private void DoOrder(Order currentOrder)
        {
            //update the db this function runes only in one thread 
            currentOrder.m_ManualResetEvent.Set();
            System.Threading.Thread.Sleep(5000);
        }
    

    其中,m\u ManualResetEvent是客户的一名成员,传递给c'tor中的每个订单

       public class Order
    {
        public ManualResetEvent m_ManualResetEvent;
        public string m_Query;
        public int m_Quntity;
    
        public Order(ManualResetEvent customerManualResetEvent, string query, int quntity)
        {
            m_ManualResetEvent = customerManualResetEvent;
            m_Query = query;
            m_Quntity = quntity;
        }
    
    }
    

    什么是最好的方法来停止等待中的线程(在**)并像c中的互斥体一样向他发出信号? 我是c#多线程新手,我的概念来自Linux内核,所以在c#中,在一个已经构建并实现了它的类中,事情可能会更容易一些。。。

    所以我的问题是‘有没有更好的设计、更好的实践、更好的方法来实现上述目标?

    1 回复  |  直到 14 年前
        1
  •  1
  •   Pieter van Ginkel    14 年前

    如果您真的只是将数据写入数据库,那么应该看看是否可以在线程本身而不是单独的线程中写入数据。如果哪怕是一点点都有可能的话,那也会为你省去很多麻烦。