【问题标题】:Is there a way to process all client requests sequentially on a .NET Framework WebAPI?有没有办法在 .NET Framework WebAPI 上按顺序处理所有客户端请求?
【发布时间】:2021-04-01 22:13:27
【问题描述】:

我最近开始使用向打印机模块发送请求的 WebAPI,但在测试过程中,我注意到当两个客户端同时发送请求时,打印机会停止并阻止所有进一步的命令。我试过这个answer here,但是 context.Request.RequestContext.RouteData 是空的。所以,我想找到一种方法来缓冲发送到 WebAPI 控制器的所有请求。我在 .NET Framework 4.5.2 上。

【问题讨论】:

  • 你考虑过使用队列吗?
  • 这就是打印服务器有打印队列的原因。请注意,您可能不希望用户在返回结果之前等待他们的工作完成。这意味着您可能希望对打印作业进行排队,而不是 API 请求。
  • @Fildor 我没有使用打印服务器,我直接将命令写入打印机。并且用户无需等待它完成,打印过程从客户端在后台异步启动。
  • @PeterBons 队列是否考虑多个客户端发出请求?我知道这将如何与单个客户端一起工作,但是当另一个请求到来时,ASP.NET 只是启动另一个线程,而不是等待当前线程完成,这正是我想要发生的。
  • 使用队列背后的想法是每个请求都添加到队列中。所以在你添加到队列的控制器动作中。另一个进程一个接一个地从队列中取出。

标签: c# asp.net-web-api


【解决方案1】:

我通过使用静态 ConcurrentQueue 并监控每个请求以锁定线程直到打印完成来解决了这个问题。它工作得很好。代码如下:

private static void tryQueue (FiscalPrinterParameters printerParameters){ 
            RequestQueue.Queue.Enqueue(printerParameters);
            bool acquiredLock = false;
            /*
             Since every API Call starts a new thread and therefore starts the printing process, 
            the RequestQueue is monitored and locked when it's used to prevent printers locking up during printing.
             */
            try
            {
                while (!acquiredLock)
                {
                    Monitor.TryEnter(RequestQueue.Queue, 500, ref acquiredLock);
                }
                if (acquiredLock)
                {
                    foreach (var item in RequestQueue.Queue)
                    {
                       /*Printer code here*/

                    }
                }
            }
            catch (Exception e) {
                Logger.Error(e);
                throw e;
            }
            finally
            {
                if (acquiredLock)
                {
                    Monitor.Exit(RequestQueue.Queue);
                }
            }
}

【讨论】:

    猜你喜欢
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多