我有一个 APIController 处理 post 请求,它正在调用静态类中的静态方法,我想返回静态类中静态字典中的下一个值。例如,收到一个请求,我想查找用于该字典的下一个索引,然后在静态属性值中将该索引增加 1。当我一次发送 1 个调用时,效果非常好,但是当 2 个调用同时进入时,它们都会从静态方法中获取保存值。
我想做的是找到一种方法来锁定静态方法,以便它可以一次处理 1 个线程,这样无论有多少个同时调用,静态方法都会同步运行。这基本上是我调用的代码。如果同时调用两次,它们都会返回相同的值,这不是我想要的。
public static class Manager
{
public static Dictionary<string, bool> ServerList { get; set; }
public static int NumberOfServers { get; set; }
public static int NextServerIndex { get; set; }
public static string GetNextServer()
{
int indextocheck = NextServerIndex;
string servername= null;
if (indextocheck >= NumberOfServers)
indextocheck = 0;
while (timer < maxtime)
{
if (ServerList.Values.ElementAt(indextocheck) == false)
{
servername = ServerList.Keys.ElementAt(indextocheck);
ServerList[server] = true;
NextServerIndex = indextocheck + 1;
break;
}
indextocheck++;
if (indextocheck == NumberOfServers)
indextocheck = 0;
}
return servername
}
}
显然我在这里遗漏了一些东西,因为我认为静态方法(在静态类中)将同步运行。我可以做什么来完成我想做的事情?
谢谢!
最佳答案
您可以使用锁
static object SpinLock = new object();
lock(SpinLock)
{
//Statements
}
就你的情况
hat I am trying to do is find a way to lock the static method so it can process 1 thread at a time so no matter how many simultaneous calls come in the static method runs synchronously. Here is basically the code I am calling. If this gets called twice at the same time they both return the same value, which is not what I want.
public static class Manager
{
static object SpinLock = new object();
// Remove the public or protect the get set with a lock
static Dictionary<string, bool> ServerList { get; set; }
static int NumberOfServers { get; set; }
static int NextServerIndex { get; set; }
public static string GetNextServer()
{
lock(SpinLock)
{
int indextocheck = NextServerIndex;
string servername= null;
if (indextocheck >= NumberOfServers)
indextocheck = 0;
while (timer < maxtime)
{
if (ServerList.Values.ElementAt(indextocheck) == false)
{
servername = ServerList.Keys.ElementAt(indextocheck);
ServerList[server] = true;
NextServerIndex = indextocheck + 1;
break;
}
indextocheck++;
if (indextocheck == NumberOfServers)
indextocheck = 0;
}
}
return servername;
}
}
关于c# - API线程和静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60214806/