簡體   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?

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

你不能只使用一個鎖來等待你需要一個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; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM