PricingHandler is injected into a BackgroundService. The question is do I need to add volatile
to the _counter
. Is Interlocked.Increment
enough to make it thread safe?
internal sealed class PricingHandler : IPricingHandler
{
private readonly ILogger<PricingHandler> _logger;
private int _counter;
public PricingHandler(ILogger<PricingHandler> logger)
{
_logger = logger;
}
public Task HandleAsync(CurrencyPair currencyPair)
{
//TODO: Implement some actual business logic
if (ShouldPlaceOrder())
{
var orderId = Guid.NewGuid().ToString("N");
_logger.LogInformation("Order with ID: {OrderId} has been placed for symbol: '{Symbol}'.", orderId, currencyPair.Symbol);
}
return Task.CompletedTask;
}
private bool ShouldPlaceOrder()
{
return Interlocked.Increment(ref _counter) % 10 == 0;
}
}