"wh" <wa***@nospam.pyesmeadow.com> wrote in message
news:di********************@newsfep2-win.server.ntli.net...
I really just need some reassurance that I'm doing the right thing really.
Here goes...
I have an object which needs to be available to all sessions. This is
being created in the Application_OnStart() event. Once created the object is
stored in the Application collection.
The idea of this global object is to manage resources (xml files) between
different sessions/users.
For example user #1 may require write access to file1.xml. If user #2
requests write access to the same file then the request will be denied.
The global object will have a method such as IsPageInUse() which will check
whether the requested page is already in use (I intend to store this
information in a collection) and return true/false accordingly.
What I'd like to know is how much support would I need to include in the
IsPageInUse() method to handle calls from multiple pages? I assume that
multiple calls can be made into the function (as opposed to one at a time
like with STA COM objects) and I will therefore need to add code to ensure
there are no race conditions when checking whether pages are in use, etc.
You're right. You have to handle the case of multiple pages touching your
object at the same time. This can be made easier by being careful to
encapsulate all accesses to your object so that it all goes through methods
and properties of your object. In particular, you must be very careful about
exposing any public fields in your object, as there is no way to control
access to them. Instead, make them public properties and control access to
them in the property setter. Gross oversimplification:
private int _counter;
public int Counter
{
get {return _counter;}
set
{
lock (this)
{
_counter = value;
}
}
}
Note that even this isn't adequate, as it doesn't save you from problems
with "object.Counter++".
If you haven't done multi-threaded programming before, let me offer a bit of
advice: Murphy rules here. Any race condition you haven't prevented from
happening _will_ happen. This is especially true when you haven't tested
under heavy load on a fast, multi-CPU system. And don't assume that because
it hasn't broken visibly, that the code is correct. It just means that you
weren't paying attention when it broke, or that it hasn't broken yet.
--
John