我们有一个多用户Web应用程序。每个用户属于他/她的组织,当然组织可以有多个用户。我需要完成的是自动编组每个组织内的文档。这是我到目前为止编写和测试的内容(下面的示例是一个测试用例,它增加了每个组织的计数器):
public class HomeController : Controller
{
private static Dictionary<int, object> lockDictionary = new Dictionary<int, object>();
private static readonly object locker = new object();
public string Lock(int orgId)
{
string path = @"X:\org_" + orgId.ToString();
lock (locker)
{
// check if orgId is in the dictionary, else add it
if (!lockDictionary.ContainsKey(orgId))
lockDictionary.Add(orgId, new object());
}
// if some other user within the same organization tries to get current counter, wait that current user finishes
lock(lockDictionary[orgId])
{
string content = "1";
// this is just testing to write to file. Actually
// the code will be: select counter from dbo.AuthOrg where orgId = x
// update dbo.AuthOrg set Counter = counter +1 where orgId = x;
if (System.IO.File.Exists(path))
{
string fileContent = System.IO.File.ReadAllText(path);
int counter = Convert.ToInt32(fileContent) + 1;
content = counter.ToString();
}
System.IO.File.WriteAllText(path, content);
System.Threading.Thread.Sleep(1000 * 10);
}
return System.IO.File.ReadAllText(path);
}
}
我需要来防止来自同一组织的两个用户在获取和增加组织计数器方面没有竞争条件。我通过使用锁来实现这一点。
上层代码是否有副作用?
应用程序托管在IIS上,因此static
变量可用于所有请求。