I am exposing an api method which accepts the request from client app. this request will be sent to another COM library where it will be validated . Based on the request data the validation may delay and return the response to my api controller.
I want to add the incoming request from (client) to a queue, and send it to COM library then get it validated. once it got validate, pick the next request from queue (if anything received during previous request being validated) for same validation process.
class ApiController : ControllerBase
{
private readonly ConcurrentQueue<RequestModel> _requestQueue = new ConcurrentQueue<RequestModel>();
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
private bool _isProcessing = false;
private readonly object _lock = new object();
public async Task<ActionResult<ValidationData>> Validate(RequestModel requestModel)
{
_requestQueue.Enqueue(requestModel);
lock (_lock)
{
if (_isProcessing)
{
return;
}
_isProcessing = true;
}
Task.Run(
async () =>
{
while (_requestQueue.TryDequeue(out var request))
{
await _semaphore.WaitAsync();
// call COM library with request data
_semaphore.Release();
}
lock (_lock)
{
_isProcessing = false;
}
});
}
}
Tried this code, but doesn't work. if the 1st request takes more time to validate, and the 2nd request getting validated before the 1st one.