C #: Generation of lock and order number (or transaction number,

Source: Internet
Author: User

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 =================================

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.