首页 > 解决方案 > 如何在asp.net web api中对请求进行排队并在服务器端执行?

问题描述

我在服务器端有使用共享数据的方法,我需要在不同请求之间同步数据访问。例如

BrowserClient1_Calling_Method1()
{
    //This should be an XHR call and it waits for the result. 
}

BrowserClient2_Calling_Method2()
{
    //This should be an XHR call and it waits for the result. 
}

在服务器端,我有两种方法需要一一调用。

//When ever this method is called, put it in some sort of queue so that 
//Method1 and Method2 gets executed one by one.  
Server_Method1()
{
    //Access the SHARED data
}


//When ever this method is called, put it in some sort of queue so that 
//Method1 and Method2 gets executed one by one.
Server_Method2()
{
    //Access the SHARED data
}

所以,我的问题是,我如何使用一些软件ConcurrentQueue并一一执行服务器方法,make client unaware of such the queue. 从客户端的角度来看,它应该像任何其他 XHR 请求一样

我尝试BlockingCollection在 c# 中使用,但不确定我应该遵循哪种模式。

请注意,我可以在 Server 方法中使用“锁定”,但我想这样做而不必使用locks.

标签: c#multithreadingasp.net-web-api2

解决方案


当您使用共享变量时,最安全和最好的做法是使用锁定模式(有多个选项可以处理此问题)

对于您问题的第二部分,最好的方法是使用异步方法,以便您的客户不知道您的队列,并且在他们的请求执行后,您可以向他们发送信号以显示相关响应(使用 signal-r)

如果您需要更多详细信息,请告诉我为您描述每个部分


推荐阅读