static methods and concurrency?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Are there any issues with concurrency on static methods creating instances
such as in the data access code below? Or if I wanted to expand it to use an
ADO.NET transaction and having two users access this method at the same time?

As I understand it, it would not be an issue because the variables being
referenced aren't static fields and are either created inside the method or
passed in.

In other words is there any real difference between this code executing
directly in a aspx codebehind vs in a static method of a class?.

public class Orders
{
public static void UpdateOrder(string value1, string value2, etc)
{
SqlConnection cn = new SqlConnection("connectionstring");
SqlCommand cmd = new SqlCommand("UpdateOrderStoredProc", cn);
...
cmd.ExecuteNonQuery();
}
}
 
Hi Dave,
you are correct, static variables can only be instantiated once per app
domain, but assigned many times. For example this does NOT compile because
this code can be executed multiple times:

static void DoSomething()
{
static int x = 5;
}

The variables inside the static function are local and are therefore
created for each thread of control that passes through them each time the
function is called, so there is no way two threads can interact with these
variables at the same time.

If you want to have static variables that are thread safe then you can use
the ThreadStaticAttribute which will allow one instance of the variable per
thread.


Mark Dawson
 
Its a static method, but your vars are instance vars, so it looks safe to me
as long as your not using any other shared vars in the method.

--
William Stacey [MVP]

| Are there any issues with concurrency on static methods creating instances
| such as in the data access code below? Or if I wanted to expand it to use
an
| ADO.NET transaction and having two users access this method at the same
time?
|
| As I understand it, it would not be an issue because the variables being
| referenced aren't static fields and are either created inside the method
or
| passed in.
|
| In other words is there any real difference between this code executing
| directly in a aspx codebehind vs in a static method of a class?.
|
| public class Orders
| {
| public static void UpdateOrder(string value1, string value2, etc)
| {
| SqlConnection cn = new SqlConnection("connectionstring");
| SqlCommand cmd = new SqlCommand("UpdateOrderStoredProc", cn);
| ...
| cmd.ExecuteNonQuery();
| }
| }
 
Dave,
All of the methods in the widely used DAAB v2 "SqlHelper" class are set up
exactly like this, as public static methods.
Peter
 

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

Back
Top