I'd like to implement an ASP.NET Core middleware (of which only one singleton instance exist) which would maintain an integer request counter, which is incremented every time a request comes in, and is decremented every time a request is finished.
public class GracetermMiddleware
{
private int requestCount = 0;
...
public async Task Invoke(HttpContext httpContext)
{
Interlocked.Increment(ref requestCount);
try
{
await next.Invoke(httpContext);
}
finally
{
Interlocked.Decrement(ref requestCount);
}
}
}
Then what I'd like to do is to have an event handler triggering when the application is stopping, to delay the termination of the process until the outstanding requests are handled. This is how I'm trying to achieve this.
private void OnApplicationStopping()
{
do
{
// Waiting for the outstanding requests to drain
Thread.Sleep(1000);
}
while (requestCount > 0);
}
(I also have some timeout handling which I omitted from the example.)
My question is: do I need to use the volatile
keyword when I declare the requestCount
field? Can it cause any issues that the field is not volatile
?