最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Queue the requests and process one by one - Stack Overflow

programmeradmin4浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论