1, What is a queue
A Queue represents a collection of first in, first out objects. Use queues when you need first in, first out access to items. When you add an item to the list, it is called joining the team. When you remove an item from the list, it is called leaving the team.
This is an excerpt from the Internet. Made a demo, but the author's technology is limited. If there is any improvement, welcome the guidance of the God.
2, Using queues to handle order issues
Idea: start a thread to create an order, and process the order thread to start at the same time. If there is an order in the queue, process it until it is not in the waiting state (here I wait 20 times to exit), and wait for the order to join the queue before continuing to process the order.
1. Create a new order OrderInfo (using structure)
public struct OrderInfo { public int OrderId { get; set; } public int ProductId { get; set; } public Decimal Price { get; set; } public string Remarks { get; set; } }
2. To control execution
class Program { public static readonly Queue queue = new Queue(); public static object obj = new object(); static void Main(string[] args) { #region Imitating Taobao to deal with order problems //Order in queue waiting Task OrderTask = new Task(CreateOrder); OrderTask.Start(); //Open thread to process order Task taskDeal = new Task(DealOrder); taskDeal.Start(); Console.WriteLine("hello"); #endregion Console.ReadKey(); } public static void CreateOrder() { for (int i = 1; i < 50; i++) { Thread.Sleep(300); lock (obj) { OrderInfo order = new OrderInfo(); order.OrderId = i; order.ProductId = 2800 + i; order.Price = 888; order.Remarks = "quick send goods"; queue.Enqueue(order); Console.WriteLine("An order was added" + i); } } } public static int flag = 0; public static void DealOrder() { while (true) { Thread.Sleep(500); if (queue.Count > 0) { lock (obj) { if (queue.Count > 0) { OrderInfo order = (OrderInfo)queue.Dequeue(); Console.WriteLine("Handle==>Order number{0};Commodity:{1}Price:{2}", order.OrderId, order.ProductId, order.Price); } } } else { Thread.Sleep(2000); flag++; if (flag > 10) { Console.WriteLine("All Over"); break; } lock (obj) { if (queue.Count <= 0) { Console.WriteLine("Order processing completed, waiting..."); } } } } } }
The test screenshot is as follows: