Critical Sections and Static Methods

  • Thread starter Thread starter blue
  • Start date Start date
B

blue

We have an abstract class with all static methods. It makes sense to have
it static because there are no member variables and the constructor is
empty.

Some of the methods update the SQL Server database and we were wondering if
there would be a problem if two threads called that method at the same time.
Would it corrupt the database?

I was thinking about locking the code on entry and unlocking it on exit.

My question is, would this work in an ASP.NET environment? Do the pages
access the same exact instance of the static classes? So, if User A
accesses the update code first and soon after, User B tries to access it,
User B will have to wait for A to unlock the code.

Thanks,

blue
 
it depends on if the code your wrote was thread safe. yes two threads can
call the exact same code address (there is no instance).

if your class has no static variables (only methods), and the parameters
passed are instance variables you should be ok.

-- bruce (sqlwork.com)
 
In case 1, static method does not access a shared resource.

In ASP.NET, if UserA and UserB calls the same static method of a
class, both threads can execute the static method at the same time
without blocking each other.

In case 2, static method does access a shared resource.

This will depend on if the shared resource is thread safe, and how
your code access the resource. Since the database is thread safe, it
will depend on how you implement the code.

If the static method access the database using only local variables,
then you won't need to lock because when ASP.NET switches between the
threads, it'll save the local variables on the thread's stack. For
example, you have local SQLConnection and SQLCommand objects.

However, if the static method uses static variables to access the
database, then you will have to lock it. Otherwise, the first thread
could close the database connection while the second thread is
accessing the database. For example, if you use a static SQLConnection
or SQLCommand object, then the object will be shared between the two
threads.

Tommy,
 
Back
Top