views:

28

answers:

2

Do We really need Locking for Static methods(Static Class) when the methods are heavily used by threads? Is it required when Static methods are using resources like SQL Queries/StoredProcedures ?

Thanks Pankaj

A: 

It entirely depends on what the static methods are doing. If they're using shared resources (e.g. the same SQL connection, or modifying a shared collection) then yes, you absolutely need locking or something similar.

If, however, each method call is effectively independent, not touching any shared mutable state, the you don't need any locking.

Jon Skeet
Static methods just execute a stored procedure that reads one or two tables and return a scalar value. I tested my methods with a threadpool of 2000 threads. It worked fine but when the code was moved to realtime production, I got the following Error"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached."my mehtod - static void sting GetValueforAccount(long AccountId){lock(object){ string value = ExecuteStoredProcedure(); return Value;}}Thnx
Panks
@Panks: Why do you have locking there? That means your connection pool is basically useless - you'll end up using just *one* connection at a time, when you could comfortably use plenty. The fact that you're *still* running out of connections suggests you may not be closing your connection (i.e. returning it to the pool) when you execute the stored procedure.
Jon Skeet
Hi Jon, You are correct, It doesn't make sense theoretically. it'd slow down the threads. I'd removed locks. I am now creating SqlConnection and SqlCommands in Using Block. That way I need not worry about explicitly closing the connections. It works now
Panks
A: 

If you have shared memory across threads (static or not) and rely on this for state information you have the potential for race conditions to occur, leading to hard to debug problems and erroneous execution.

hydrogen