Critical Sections and Static Methods

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
 
B

bruce barker

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)
 
T

Tommy

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,
 

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

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top