Solution: Thread-Safe Voucher Redemption

Review how to use the lock statement to safely evaluate and mutate shared state to prevent double-spending in concurrent environments.

Solution: Thread-Safe Voucher Redemption

Review how to use the lock statement to safely evaluate and mutate shared state to prevent double-spending in concurrent environments.
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;
}
}
}