I have a private static field in my Controller class in an MVC web application.
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:-
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). 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; }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.