0

我在 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();
        }
4

1 回答 1

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; }
}
于 2011-03-26T13:29:14.147 回答