Search⌘ K
AI Features

Solution: Thread-Safe Voucher Redemption

Understand how to implement thread-safe voucher redemption by using a mutual exclusion lock to avoid race conditions in concurrent requests. Explore asynchronous programming with Task.Run and await to handle multiple threads efficiently, ensuring only one thread redeems the voucher successfully.

We'll cover the following...
C# 14.0
using System.Threading;
namespace ECommerce;
public class VoucherService
{
public bool IsVoucherUsed { get; private set; } = false;
private readonly object _voucherLock = new object();
public bool RedeemVoucher()
{
lock (_voucherLock)
{
if (!IsVoucherUsed)
{
// Simulate random network/database delay
Thread.Sleep(new Random().Next(10, 100));
IsVoucherUsed = true;
return true;
}
return false;
}
}
}
...