473,750 Members | 2,190 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Microsoft Data Access Block and static methods

Hey all -

Excuse the cross-post ... I'm not sure what the appropriate newsgroup
would be for this question.

I have a question that I'm not quite sure how to ask. For all I know, I
have the verbaige completely wrong, but here goes nothing ...

I'm currently using the MS Data Access Block for a desktop application
I'm writing. Recently, I had to add a call to a web service, which in
itself calls a mssql database. I had figured that I would just use the
MS DAL as I was in the client app, but then found myself confused about
something: How can a web service, with multiple people connecting to it
at any given time, use a static method to get it's data?

In past experiences with ASP.NET applications, if I had a static
variable declared and set by one User A, User B browsing to that page
would see the new value set by A. Isn't the same possible for database
calls? If User A calls my web service at the same time User B calls it,
isn't it possible that B might get A's result, or vice versa?

I think it might come down to my idea of how static variables work: I
look at the MSDN docs and see that SqlCommand has the following:

"Any public static (Shared in Visual Basic) members of this type are
safe for multithreaded operations. Any instance members are not
guaranteed to be thread safe."

I would figure it to be completely opposite - that if multiple threads
are hitting a static member, it'd be possible those results could get
returned to the wrong user, whereas in an instance member, each method
being called is a separate logical piece, so there's no results being
misguided.

Can anyone help me out with this? I'm not new to the programming world,
but for some reason I'm finding this really confusing.
Thanks in advance!
Clint

Nov 16 '05 #1
9 4160
Most of the methods in the DAB are stateless. The methods use only the
incoming parameters and local variables. The problem you faced in
ASP.NET development was using a static variable to store information.
Think of it as having only one "slot" available to store a piece of
data so every user sees the data from the single slot.

There are a few static fields in the DAB (for SqlParameter caching, if
I remember), but these fields are guarded with locks to prevent
concurrent threads from screwing it up, and the data (information
about what SqlParameters are required by a stored procedure) is global
for every user.

Making any sense?

As for the MSDN docs, they are saying that the static member methods
are written to be thread safe, so they have to use locks where
appropriate. MS assumes the framework is going to be used in a
multithreaded environment and couldn't let static methods not be
thread safe.

That being said, instance members are not safe because a single
instance of an object is typically not going to be used by multiple
threads. In ASP.NET for instance, you typically create an instance of
a class for each user request - a TextBox control will never see
multiple threads. Since locks add some performance overhead (and a lot
of development and testing overhead), the decision makes a great deal
of sense, even if it looks counterintuitiv e at first.

--
Scott
http://www.OdeToCode.com/blogs/scott/
On 9 Dec 2004 13:48:02 -0800, "Clint" <cj*******@gmai l.com> wrote:
Hey all -

Excuse the cross-post ... I'm not sure what the appropriate newsgroup
would be for this question.

I have a question that I'm not quite sure how to ask. For all I know, I
have the verbaige completely wrong, but here goes nothing ...

I'm currently using the MS Data Access Block for a desktop application
I'm writing. Recently, I had to add a call to a web service, which in
itself calls a mssql database. I had figured that I would just use the
MS DAL as I was in the client app, but then found myself confused about
something: How can a web service, with multiple people connecting to it
at any given time, use a static method to get it's data?

In past experiences with ASP.NET applications, if I had a static
variable declared and set by one User A, User B browsing to that page
would see the new value set by A. Isn't the same possible for database
calls? If User A calls my web service at the same time User B calls it,
isn't it possible that B might get A's result, or vice versa?

I think it might come down to my idea of how static variables work: I
look at the MSDN docs and see that SqlCommand has the following:

"Any public static (Shared in Visual Basic) members of this type are
safe for multithreaded operations. Any instance members are not
guaranteed to be thread safe."

I would figure it to be completely opposite - that if multiple threads
are hitting a static member, it'd be possible those results could get
returned to the wrong user, whereas in an instance member, each method
being called is a separate logical piece, so there's no results being
misguided.

Can anyone help me out with this? I'm not new to the programming world,
but for some reason I'm finding this really confusing.
Thanks in advance!
Clint


Nov 16 '05 #2
Clint,

I had the very same question a few days back - and I wrote up a quick neato
sample. Basically I had a class with a static method, doing a
console.writeli ne of the thread id it was in. I then fired off 2 threads and
called the same class repeatedly and to my surprise the static method
returned me ... different thread ids. Very enthused, I wrote up another
sample in which I put a 5 minute sleep in the static - and well if the very
same instance was being shared either thread would have to wait 5 minutes
before being able to use the ONE COMMON instance - ... and to my suspection
... it didn't !!!! Which led me to believe that ---

Even static methods are created on each thread - but within the thread there
is one and only one instance. Every thread gets it's own private copy of a
static method.

So there - static methods are threadsafe which is why the famous line -- "
"Any public static (Shared in Visual Basic) members of this type are
safe for multithreaded operations. Any instance members are not
guaranteed to be thread safe."
"

What do they mean by instance members? Well what that means is, if you have
module level static methods, then two threads will actually share the same
value, and you need mutexes or some other method to lock access to those -
or you might get unexpected values in them. But methods - are cool !! module
level variables are not cool.

So go ahead use the DAB without worrying about statics :)

- Sahil Malik
http://dotnetjunkies.com/weblog/sahilmalik
http://blogs.apress.com/authors.php?author=Sahil Malik


"Clint" <cj*******@gmai l.com> wrote in message
news:11******** *************@z 14g2000cwz.goog legroups.com... Hey all -

Excuse the cross-post ... I'm not sure what the appropriate newsgroup
would be for this question.

I have a question that I'm not quite sure how to ask. For all I know, I
have the verbaige completely wrong, but here goes nothing ...

I'm currently using the MS Data Access Block for a desktop application
I'm writing. Recently, I had to add a call to a web service, which in
itself calls a mssql database. I had figured that I would just use the
MS DAL as I was in the client app, but then found myself confused about
something: How can a web service, with multiple people connecting to it
at any given time, use a static method to get it's data?

In past experiences with ASP.NET applications, if I had a static
variable declared and set by one User A, User B browsing to that page
would see the new value set by A. Isn't the same possible for database
calls? If User A calls my web service at the same time User B calls it,
isn't it possible that B might get A's result, or vice versa?

I think it might come down to my idea of how static variables work: I
look at the MSDN docs and see that SqlCommand has the following:

"Any public static (Shared in Visual Basic) members of this type are
safe for multithreaded operations. Any instance members are not
guaranteed to be thread safe."

I would figure it to be completely opposite - that if multiple threads
are hitting a static member, it'd be possible those results could get
returned to the wrong user, whereas in an instance member, each method
being called is a separate logical piece, so there's no results being
misguided.

Can anyone help me out with this? I'm not new to the programming world,
but for some reason I'm finding this really confusing.
Thanks in advance!
Clint

Nov 16 '05 #3
Thanks Sahil!

If you don't mind, I just have a few more questions on top of those
already answered, just to make sure I understand whats actually going
on.
Even static methods are created on each thread - but within the thread there is one and only one instance. Every thread gets it's own private copy of a static method.
Let's pretend for a second that I have a client app that uses MDI forms
- call one MDI Child Profile, the other Search.
That said, I have a utility class,
class Foo
{
public static DataSet StaticDatabaseQ ueryMethod()
{
// do something that returns a DataSet
}
}

In MDIChild Profile, a timer spawns a thread that calls
Foo.StaticDatab aseQueryMethod( ) that will return the user's profile. At
the same time, the user is really looking at the Search MDI Child form,
and search that spawns it's own thread and performs the search - again
- using Foo.StaticDatab aseQueryMethod( ).

If I'm understanding right, I have three threads running (Main GUI,
Profile query, and Search query). Because these are on separate
threads, the two queries can both access the static Foo member, and
will not have any issues with data being returned to the wrong form
(ie, Profile's return set goes to Search, and vice versa)?
What do they mean by instance members? Well what that means is, if you have module level static methods, then two threads will actually share the same value, and you need mutexes or some other method to lock access to those - or you might get unexpected values in them. But methods - are cool !! module level variables are not cool.


In other words, using static for methods is ok, but static for fields
within a class isn't?

Another example, sorry :)
class Foo
{
private static string fooField; // this is a bad idea, and will
require lock(...) when accessing
private static string fooMethod() {} // this is OK to do, and will
return correct values so long as it's called by separate threads
}

Thanks again!
Clint

Nov 16 '05 #4
Thanks, Scott!

The first part of your post did in fact clear up the big hangup I had
w/the MS DAL. I'd just like to try to clarify a few points, though ...
sorry for the constant questions, I just want to make sure I have this
fully understood before I make a big mistake that would cause quite a
lot of problems if data gets mixed up :)

----------
MS assumes the framework is going to be used in a multithreaded
environment and couldn't let static methods not be thread safe.
----------

So I don't have to worry about adding my own lock(...) commands when
referencing MS-written static methods, but if I'm writing my own static
methods that reference static fields in a class, I should use
lock(...)?
ie,

class Foo
{
private static string testValue;

public static void AdjustTestValue ()
{
lock (this) // or lock(typeof(Foo ))?
{
testValue = "something" ;
}
}
}

----------
That being said, instance members are not safe because a single
instance of an object is typically not going to be used by multiple
threads. In ASP.NET for instance, you typically create an instance of a
class for each user request - a TextBox control will never see multiple
threads. Since locks add some performance overhead (and a lot of
development and testing overhead), the decision makes a great deal of
sense, even if it looks counterintuitiv e at first.
----------

I'm having trouble understanding this ... do you mean that in an
ASP.NET (and, for my purpose, Web Services), I should be instantiating
classes instead of using statics, or that it's ok to use statics in
that each request is processed on it's own thread, so long as I don't
actually STORE a value in a static field(ex, inside the static method,
I perform a SQL query only, not storing the result of that query to a
static field)?

Thanks again!
Clint

Nov 16 '05 #5
Clint .. answer to Q#1 - Yes, as long as the implementation of
StaticDatabaseQ ueryMethod doesn't rely on instance members that are static.

Answer to Q#2 - Yes you need a locking mechanism to access that variable to
ensure data sanctity.

- Sahil Malik
http://dotnetjunkies.com/weblog/sahilmalik


"Clint" <cj*******@gmai l.com> wrote in message
news:11******** *************@f 14g2000cwb.goog legroups.com...
Thanks Sahil!

If you don't mind, I just have a few more questions on top of those
already answered, just to make sure I understand whats actually going
on.
Even static methods are created on each thread - but within the

thread there
is one and only one instance. Every thread gets it's own private copy

of a
static method.


Let's pretend for a second that I have a client app that uses MDI forms
- call one MDI Child Profile, the other Search.
That said, I have a utility class,
class Foo
{
public static DataSet StaticDatabaseQ ueryMethod()
{
// do something that returns a DataSet
}
}

In MDIChild Profile, a timer spawns a thread that calls
Foo.StaticDatab aseQueryMethod( ) that will return the user's profile. At
the same time, the user is really looking at the Search MDI Child form,
and search that spawns it's own thread and performs the search - again
- using Foo.StaticDatab aseQueryMethod( ).

If I'm understanding right, I have three threads running (Main GUI,
Profile query, and Search query). Because these are on separate
threads, the two queries can both access the static Foo member, and
will not have any issues with data being returned to the wrong form
(ie, Profile's return set goes to Search, and vice versa)?
What do they mean by instance members? Well what that means is, if

you have
module level static methods, then two threads will actually share the

same
value, and you need mutexes or some other method to lock access to

those -
or you might get unexpected values in them. But methods - are cool !!

module
level variables are not cool.


In other words, using static for methods is ok, but static for fields
within a class isn't?

Another example, sorry :)
class Foo
{
private static string fooField; // this is a bad idea, and will
require lock(...) when accessing
private static string fooMethod() {} // this is OK to do, and will
return correct values so long as it's called by separate threads
}

Thanks again!
Clint

Nov 16 '05 #6
Hi Clint:


So I don't have to worry about adding my own lock(...) commands when
referencing MS-written static methods, but if I'm writing my own static
methods that reference static fields in a class, I should use
lock(...)?
ie,

It's always good to check the docs, but generally the MS static
methods are thread safe.
class Foo
{
private static string testValue;

public static void AdjustTestValue ()
{
lock (this) // or lock(typeof(Foo ))?
{
testValue = "something" ;
}
}
}
Yes, a lock would be needed. Remember you can't use "this" in a static
method. Jon has a good article on picking what to lock on:
http://www.yoda.arachsys.com/csharp/...ml#lock.choice

----------
That being said, instance members are not safe because a single
instance of an object is typically not going to be used by multiple
threads. In ASP.NET for instance, you typically create an instance of a
class for each user request - a TextBox control will never see multiple
threads. Since locks add some performance overhead (and a lot of
development and testing overhead), the decision makes a great deal of
sense, even if it looks counterintuitiv e at first.
----------

I'm having trouble understanding this ... do you mean that in an
ASP.NET (and, for my purpose, Web Services), I should be instantiating
classes instead of using statics, or that it's ok to use statics in
that each request is processed on it's own thread, so long as I don't
actually STORE a value in a static field(ex, inside the static method,
I perform a SQL query only, not storing the result of that query to a
static field)?


It is OK to use static methods in a multithreaded app, the place to be
very careful is when using static fields.

--
Scott
http://www.OdeToCode.com/blogs/scott/
Nov 16 '05 #7
Excellent - that clears up a lot.

Thanks again!

Nov 16 '05 #8
Makes perfect sense - thanks again, Sahil!

Nov 16 '05 #9
"If User A calls my web service at the same time User B calls it, isn't
it possible that B might get A's result, or vice versa?"

You could set EnableSessionSt ate to true in the WebMethod atribute so
that the webservice could maintain the state for the client until the
method completes its execution. Anyway, it is not just session state
that is important when using a webservice as a Data Access Layer, it is
also the TransactionCont ext. More on transactions in Web Services upon
your reply.
"Any public static (Shared in Visual Basic) members of this type are afe
for multithreaded operations. Any instance members are not guaranteed to
be thread safe."

"I would figure it to be completely opposite - that if multiple threads
are hitting a static member, it'd be possible those results could get
returned to the wrong user, whereas in an instance member, each method
being called is a separate logical piece, so there's no results being
misguided."

It is not the opposite, though, you would need to lock the application
state, if you are talking about the ASP.Net environment (and if you are
not, I am), before writing or accessing a static member.
with regards,
J.V.Ravichandra n
- http://www.geocities.com/
jvravichandran
- http://www.411asp.net/func/search?
qry=Ravichandra n+J.V.&cob=aspn etpro
- http://www.southasianoutlook.com
- http://www.MSDNAA.Net
- http://www.csharphelp.com
- http://www.poetry.com/Publications/
display.asp?ID= P3966388&BN=999 &PN=2
- Or, just search on "J.V.Ravichandr an"
at http://www.Google.com

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3771
by: Ovid | last post by:
Hi, I'm trying to determine the cleanest way to override class data in a subclass. class Universe { public String name; private static double PI = 3.1415; Universe(String name) {
4
8031
by: Neil Zanella | last post by:
Hello, I would like to know whether it is possible to define static class methods and data members in Python (similar to the way it can be done in C++ or Java). These do not seem to be mentioned in "Learning Python" by Mark Lutz and David Ascher. It seems like they are a relatively new feature... It seems to me that any truly OO programming language should support these so I'm sure that Python is no exception, but how can these be...
4
3862
by: Thomas Paul Diffenbach | last post by:
Can anyone point me to an open source library of /statically allocated/ data structures? I'm writing some code that would benefit from trees, preferably self balancing, but on an embedded system that doesn't offer dynamic memory allocation (to be clear: no malloc, no realloc), and with rather tight memory constraints. Writing my own malloc to do dynamic allocation from some static pool isn't really an option, for various reasons, not...
6
2153
by: Dan | last post by:
Hi Is Microsoft's Sqlhelper.cs (Microsoft Application Blocks for .NET - Data Access) Thread safe? The documentation has no references to threads. Thanks Dan
6
1903
by: VidalSasoon | last post by:
I have a singleton class that I want to only contain a hashtable. I want to be able to modify this hashtable at will. The problem I am having is each time I try to update the data using the "SetState" method, "_Instance" keeps on getting reset. I have a hard time grasping the idea how a singleton just holds the data... anyway, here's my test code for console if anyone can help. V.
3
1422
by: ahaupt | last post by:
Hi all, At the moment we use static methods for retrieving data: Ex. DataTable supplierDT = DAC.Supplier.GetAll(); DataTable customerDT = DAC.Customer.GetAll(); The reason we use static methods is that it's not really worth the
3
1620
by: Mark Gilkes | last post by:
I would just like to get a feeling for what others are doing here. Having read through the 'Data Tiers' paper under MS's Paterns and Practices I am designing and developing a small(ish) 3 layered web app. Now I've come to design the DALC classes I cannot see any reason why I would make these methods instance methods. It seems to me that they only need be static methods. The DALC is purely a class definition with a bunch of methods that...
3
1817
by: Mukesh | last post by:
Hi all As per my earlier conversation with Ciaran (thx for reply) I have installed the MS APplication block on the server , when i ran Build Enterprise Library file and Install Services from (batch files ) programme files menu it was asking for visual studio 2003 , I have only .net framework on the server how can i use the MS application block data access library on my server plz help... Mukesh Agarwal
4
4531
by: Dave | last post by:
I have a global.asax file with Application_Start defined and create some static data there and in another module used in the asp.net application and I realize that static data is shared amongst child apps of an IIS application and can be used by multiple users during the application life cycle and for multiple page loads for the same or different page under a root application. What I don't understand and need to know is whether that...
0
8999
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9575
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9394
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9338
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8260
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6080
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4885
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2798
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2223
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.