Static - Thread Safe?

R

reyesflaco

I am developing an application using asp.net 2.0. I created all my
business objects in my app_code folder. As of right now, all my
classes are public.

In my aspx pages, I am declaring the class like so

static Person myPerson;

The static declaration is working for me, for It keeps the instance of
the class open through the lifetime of the user who is logged in.
However, I read that the reference remains open even after the user's
session, and it is probably not going to be thread safe? I want to
avoid storing it in a Session due to it being rather expensive on the
server. I could probably make the class private, and ensure that the
class is instantiated accordingly. Any suggestions from you experts?
 
A

AlexS

I believe any global object is not thread-safe by definition if you don't
synchronize access to fields/methods properly

If your Person is related to user/session, probably you would be better off
by making it in-session instance. Just destroy it when closing session and
you should be pretty safe.
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

I am developing an application using asp.net 2.0. I created all my
business objects in my app_code folder. As of right now, all my
classes are public.

In my aspx pages, I am declaring the class like so

static Person myPerson;

The static declaration is working for me, for It keeps the instance of
the class open through the lifetime of the user who is logged in.
However, I read that the reference remains open even after the user's
session, and it is probably not going to be thread safe? I want to
avoid storing it in a Session due to it being rather expensive on the
server. I could probably make the class private, and ensure that the
class is instantiated accordingly. Any suggestions from you experts?

Thread safety is not a problem if you have data that is local to the
thread. A static variable however, is not local to the thread. What you
have is a single Person object that is shared by all threads, which
means that your application only can handle a single user.

Making it private makes no difference either. That only means that it's
private to the class where you declared it, not private to the thread.

If you want to store user specific data, you have to use user specific
storage, like Session variables.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top