Static keyword usage in asp.net?

G

Guest

I'm trying to understand the implications of using static methods and
properties in asp.net so I found an article "Troubleshooting ASP.NET
applications with the use of static keywords"
(http://support.microsoft.com/?id=893666) that discusses the possiblity of
users seeing other users data if they access static methods at the same time
because values are shared.

Although I never used it, I noticed that some SqlHelper functions part of
the Data Access application block use static methods (i.e ExecuteReader) Why
would this be if there is a risk of race conditions as described in the
article?

It seems static should be used very sparingly in asp.net app (as opposed to
say a desktop smart client app where each user would have their own copy of
static methods/properies) Is this a fair assessment??

Thanks
 
K

Keith Patrick

You are just going to have to be more aware of threading issues, as
threading is implicitly done in an ASP.Net app, as opposed to something like
a WinForms app, since the application server (IIS) is inherently threaded
due to supporting multi-users via threaded request handlers.
A static method is going to be thread-safe if it is properly implemented for
this kind of usage. Basically, as long as the method creates all of its
variables locally and grabs its DB connection (if it's a DB method) from the
pool (which itself is threadsafe), there isn't going to be a race condition,
as the shared resources (connections) are handled in a threadsafe manner,
while all other vars used in the method are created locally and thus not
shared across method calls.
 
P

Patrice

Because a method is "executable code" and is not updated. The problem is
with what multiple users could update (i.e. variables).

See an ASP.NET application as being the SAME application used by MULTIPLE
users...
 
K

Keith Patrick

Or, in simpler terms, you'll run into problems if your method is static
because you are using a class (as opposed to an instance of the class) as a
singleton rather than as a respository of self-contained, atomic method
calls.
 
P

Peter Rilling

In addition to the other responses, there is a difference between "static"
at the method and at the variable level.

Most of the time a method that is static is simply a helper, it takes some
input and returns the result. No state is saved. For instance, many of the
methods on the Math class are static because you simply pass numbers in the
methods and get a result back.

So, simply because SqlHelper.ExecuteReader is static, that does not mean
that it will have security or threading problems.

Now, sometimes you do want to maintain static with static methods. For
instance, in a singleton pattern, you will have some factory method that
returns an instance of the object, the object will be saved in some variable
that will also be static for later use. In this case you would have
problems.
 
G

Guest

Scott,

Can there be threading or deadlock issues by calling the same static method
back-to-back (but with different params)?

I'm calling a static method of a class two or more times that will initiate
a WebRequest.BeginGetResponse() because I'm trying perform asynchronous
webrequests.

I then use the WaitHandle.WaitAll to wait for a signal from each
IAsynch.AsynchWaitHandle. When I comment out either one of the calls, the
app responds, otherwise when I try to call both it just hangs.

Thanks, Dave.
 
S

Scott Allen

Hey Dave:

There isn't any problem with calling a static method concurrently. Are
you sure none of the variables you use in the method aren't static?
Any chance you can share a code snippet that demonstrates the problem?
 
G

Guest

Scott,

I'm trying to make aynch webrequests below using the
BeginGetResponse/EndGetResponse code below. I call the BeginGetResponse for
each url I call that returns XML, then pass the webrequest back as part of
the state of the IAsynchResult.

I then wait for the IAsynchResult handles to return before I call the
EndGetResponse for each.

Is there a suggested limit as to how many of these asynch calls I can make?
Unfortunately I have about 10 to make and if I try 8 or 9, the
BeginGetResponse seems to time out when I call it.

Is this approach feasible? I'm wondering if I'm using up too many threads
but the request timeout doesn't tell me much. I may be getting beyond the
scope of my initial post. Thanks, Dave.

CODE:
-------

public class HttpUtility
//Static methods to make asynch webrequest...

{

public static System.IAsyncResult BeginMakeHttpRequest(strUrl)
{

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strUrl);

req.Timeout = GetTimeout();

System.IAsyncResult ar = req.BeginGetResponse(null, req);

return ar;
}


public static string EndMakeHttpRequest(System.IAsyncResult ar)
{
// Return the response.
HttpWebRequest req = (HttpWebRequest) ar.AsyncState;
HttpWebResponse resp = (HttpWebResponse) req.EndGetResponse(ar);

//Wrap the response stream with a text-based reader
StreamReader sr = new StreamReader(resp.GetResponseStream());

string strStream = sr.ReadToEnd();

// Close the response to free resources.
sr.Close();
resp.Close();

return strStream;
}

}

//.aspx calling the asynch requests...

System.IAsyncResult ar1 =
BeginMakeHttpRequest("http://SomeSite.com/GetXml1.asp");
System.IAsyncResult ar2 =
BeginMakeHttpRequest("http://SomeSite.com/GetXml2.asp");
etc...

//create an array of handles
WaitHandle[] wh = {ar1.AsyncWaitHandle, ar2.AsynchWaitHandle, etc...};

//Wait for the handles to get a signal
if (WaitHandle.WaitAll(wh, 60000, false))
{
string strXml1 = HttpUtility.EndMakeHttpRequest(ar1);
string strXml2 = HttpUtility.EndMakeHttpRequest(ar2);
etc.
//I compile an Xml document here to create a report from the
different sources.
}
 
S

Scott Allen

Is there a suggested limit as to how many of these asynch calls I can make?
Unfortunately I have about 10 to make and if I try 8 or 9, the
BeginGetResponse seems to time out when I call it.

You might be running into a problem because .NET only allows 2
simultaneous outbound connections to the same server using HTTP. This
is configurable, I have more details here:
http://odetocode.com/Blogs/scott/archive/2004/06/08/272.aspx

Is this approach feasible? I'm wondering if I'm using up too many threads
but the request timeout doesn't tell me much. I may be getting beyond the
scope of my initial post. Thanks, Dave.

You have to be careful in asp.net not to tie up too many of the worker
threads - there is a limited amount. Any chance you are using 2.0? You
could use the AsynchPage feature to free up some threads.
 
G

Guest

Thanks, that sounds like it could be the issue. I added the following to my
app's web.config

<configuration>
<system.web>
<connectionManagement>
<add name = "*" maxconnection = "40" />
</connectionManagement>
.....
but get this when I start the app:

Message: Unrecognized configuration section 'connectionManagement' .
According to MSDN I should be able to add it here "This element can be used
in the application configuration file, the machine configuration file
(Machine.config), and the publisher policy file."
 
G

Guest

Scott,

Ok, I changed the machine.config and it worked. That seemed to be the
trick! Thanks!

Unfortunately, I have to get this to work with 1.1 for now. Dave.
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top