简体   繁体   English

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

[英]How can I lock a private static field of a class in one static method and then release it in some other instance method?

I have a private static field in my Controller class in an MVC web application. 我在MVC Web应用程序的Controller类中有一个私有静态字段。

I have a static method in that controller that assigns some value to that static field, I want to apply lock on that static field until some other instance method in the controller uses the value stored in the static field and then releases it. 我在该控制器中有一个静态方法为该静态字段赋值,我想在该静态字段上应用锁,直到控制器中的某个其他实例方法使用存储在静态字段中的值然后释放它。

How can I do this ? 我怎样才能做到这一点 ?

DETAILS: 细节:

I have a controller named BaseController having a static ClientId field as follows and two methods as follows:- 我有一个名为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();
        }

You can't just use a lock to wait you need an AutoResetEvent (or equivalent). 你不能只使用一个锁来等待你需要一个AutoResetEvent(或等价物)。 Something like this may prove useful : 这样的事情可能有用:

// 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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM