I have a WCF service that processes transactions. It first generates a reference number based on the last reference number in the database + 1, then assists the reference number to the wcf request message it received, and then saves all the information in the request to the database.
I had an issue where duplicate reference numbers were generated, which was a typical race condition.
I implemented the following code to insure that only one request can generate a new reference number and save that to the database.
Will I be guaranteed that only ONE request will be able to execute the block of code within the mutex at a time?
private static Mutex waitForDBInsert = new Mutex();
protected override PostPaymentResponse PostPayment(PostPaymentRequest request)
{
var response = new PostPaymentResponse();
try
{
// Save to transaction and payee to database
if (request.PaymentDetails.PaymentID == 0)
{
waitForDBInsert.WaitOne();
// Generate next available transactions reference number.
response.PaymentDetails.ReferenceNumber = GenerateReferenceNumber(null);
// Save transaction to database before processing.
var saveToDbResponse = SaveFXPaymentToDatabase(request, response);
waitForDBInsert.ReleaseMutex();
}
}
catch (Exception ex)
{
if (!waitForDBInsert.SafeWaitHandle.IsClosed)
waitForDBInsert.ReleaseMutex();
}
return response;
}
Yes, if it's a global mutex. See the code for class SingleGlobalInstance
posted in this SO thread for a great example: What is a good pattern for using a Global Mutex in C#?
Also, as already commented, you should also strongly consider using an auto-incremented column instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.