C #: Generation of lock and order number (or transaction number,
For e-commerce websites, the order number (yyyyMMddHHmmss) is usually generated based on the format of year, month, day, minute, and second. To solve the concurrency, the lock is directly added to the area block where the order number is generated.
Next, let's perform a simple test.
1. Create a project (console application)
2. Create a new class: OrderIdHelper. cs
1 /// <summary> 2 // order assistant 3 /// </summary> 4 class OrderIdHelper 5 {6 private static readonly object Locker = new object (); 7 private static string _ tempId = ""; 8 9 // <summary> 10 // generate Order Number 11 /// </summary> 12 public static void GenerateId () 13 {14 lock (Locker) // The lock keyword ensures that when one thread is located in the Code critical section, the other thread does not enter the critical section. 15 {16 var orderId = "Wen" + DateTime. now. toString ("yyyyMMddHHmmss"); // year, month, day, hour, minute, second, 17 18 if (string. equals (_ tempId, orderId) 19 {20 throw new Exception ("Duplicate order number! "); 21} 22 23 _ tempId = orderId; 24 25 Console. WriteLine (orderId); 26} 27} 28}View Code
3. Program. cs
1 class Program 2 {3 static void Main (string [] args) 4 {5 // create an array containing two threads 6 var threads = new Thread [2] 7 {8 new Thread (OrderIdHelper. generateId), 9 new Thread (OrderIdHelper. generateId), 10}; 11 12 foreach (var thread in threads) 13 {14 // thread starts 15 threads. start (); 16} 17 18 Console. read (); 19} 20}View Code
4. Result: ==== OrderIdDemo_1.rar. Click my download ====
5. ==================================== unfinished, to be continued =================================