如何在一个静态方法中锁定类的私有静态字段,然后在其他实例方法中释放它?

时间:2011-03-26 10:18:45

标签: c# asp.net multithreading asp.net-mvc-2 locks

我在MVC Web应用程序的Controller类中有一个私有静态字段。

我在该控制器中有一个静态方法为该静态字段赋值,我想对该静态字段应用锁,直到控制器中的某个其他实例方法使用存储在静态字段中的值然后释放它。

我该怎么做?

详情:

我有一个名为BaseController的控制器,它有一个静态ClientId字段,如下所示,有两种方法: -

public static string ClientId = "";

static void OnClientConnected(string clientId, ref Dictionary<string, object> list)
        {
            list.Add("a", "b");
// I want the ClientId to be locked here, so that it can not be accessed by other requests coming to the server and wait for ClientId to be released:-
            BaseController.clientId = clientId; 
        }

public ActionResult Handler()
        {
            if (something)
            {
                // use the static ClientId here
            }
// Release the ClientId here, so it can now be used by other web requests coming to the server.
            return View();
        }

1 个答案:

答案 0 :(得分:2)

你不能只使用锁来等待你需要一个AutoResetEvent(或等效的)。这样的事情可能有用:

// Provide a way to wait for the value to be read;
// Initially, the variable can be set.
private AutoResetEvent _event = new AutoResetEvent(true);

// Make the field private so that it can't be changed outside the setter method
private static int _yourField;

public static int YourField {
    // "AutoResetEvent.Set" will release ALL the threads blocked in the setter.
    // I am not sure this is what you require though.
    get { _event.Set(); return _yourField; }

    // "WaitOne" will block any calling thread before "get" has been called.
    // except the first time
    // You'll have to check for deadlocks by yourself
    // You probably want to a timeout in the wait, in case
    set { _event.WaitOne(); _yourField = value; }
}