Reputation: 47
in asp.net web application if I want to store variable in a static object is that right? I don't want that this object will share its value with another request.
public static object Objects
{
get
{
if (HttpContext.Current.Items["Objects"] != null)
return (object)HttpContext.Current.Items["Objects"];
else
{
HttpContext.Current.Items["Objects"] = new object();
return new object();
}
}
set { HttpContext.Current.Items["Objects"] = value; }
}
THX
Upvotes: 0
Views: 2744
Reputation: 172606
Static fields are shared across the whole AppDomain. This means that ALL requests in a ASP.NET web application will use the same value and you will have to make sure that variable is thread-safe. If this is not what you want, consider the following:
HttpContext.Current.Session
HttpContext.Current.Items
. This way the value is cached throughout the current request, but not shared across requests.In your case however, you are using a static
property. This static property maps in your case to the HttpContext.Current.Items
, which means that each request automatically gets its own variable and variables are not shared.
In other words, your code is thread-safe.
Upvotes: 3
Reputation: 1839
There are 4 main server Dictionary objects that store values between requests. Application - shares values between all requests and users. Cache - shares values between all requests and users but can be invalidated without restarting application. Session - shares values between requests within the same session, all pages share the same session object, and is user specific. ViewState - shares values between request but is page specific and user specific.
Upvotes: 0
Reputation: 186
if you want the benefit of static across a single request. That is, have a single request have access to the same value. Use a session variable instead.
Session['variable'] = value
this will store the value in the current session, this way you will have a different value per request.
Upvotes: -2
Reputation: 460018
If you want to use a static variable without sharing it across all requests you could store a session variable in a static property. Use HttpContext.Session
to access it.
public static object Objects
{
get
{
if (HttpContext.Current.Session["Objects"] != null)
return (object)HttpContext.Current.Session["Objects"];
else
{
var obj = new object();
HttpContext.Current.Session["Objects"] = obj;
return obj;
}
}
set { HttpContext.Current.Session["Objects"] = value; }
}
However, you should not return object
but the correct type, that will increase readability, prevents exceptions and avoids always casting it where you use it.
Upvotes: 1
Reputation: 148110
I don't want that this object will share its value with another request.
You should not make it static then.
Upvotes: 1