473,320 Members | 1,868 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

static constructor and multithreading

Hi,

I am analyzing Duwamish7 source code boundled with Visual Studio .NET 2003.
Could anoybody explain why the Monitor.Enter and Monitor.Exit block is used
inside a static constructor? The code can be found in Project
SystemFramework within module ApplicationLog.cs. Here comes the sample.

namespace Duwamish7.SystemFramework {

(some code...)

public class ApplicationLog {
(some code..)
static ApplicationLog() {
Type myType = typeof(ApplicationLog);
try {
if (!Monitor.TryEnter(myType)) {
Monitor.Enter(myType);
return;
}
(some code..)
}
finally {
Monitor.Exit(myType);
}

} // static constructor

} // class ApplicationLog

(some code..)

} //namespace Duwamish7.SystemFramework

Mark
Nov 16 '05 #1
10 2489
Marek,

It is possible that there are other areas of the code that are using the
type of ApplicationLog as the object on which to lock a section of code.
Getting the Type of a class doesn't cause static constructor code to fire
(using typeof).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
"Marek" <ma**************@sbcglobal.net> wrote in message
news:XU********************@newssvr28.news.prodigy .com...
Hi,

I am analyzing Duwamish7 source code boundled with Visual Studio .NET 2003. Could anoybody explain why the Monitor.Enter and Monitor.Exit block is used inside a static constructor? The code can be found in Project
SystemFramework within module ApplicationLog.cs. Here comes the sample.

namespace Duwamish7.SystemFramework {

(some code...)

public class ApplicationLog {
(some code..)
static ApplicationLog() {
Type myType = typeof(ApplicationLog);
try {
if (!Monitor.TryEnter(myType)) {
Monitor.Enter(myType);
return;
}
(some code..)
}
finally {
Monitor.Exit(myType);
}

} // static constructor

} // class ApplicationLog

(some code..)

} //namespace Duwamish7.SystemFramework

Mark

Nov 16 '05 #2
> It is possible that there are other areas of the code that are using
the
type of ApplicationLog as the object on which to lock a section of code.
Getting the Type of a class doesn't cause static constructor code to fire
(using typeof).

Does that mean that a static ctor could be called more than once?

--
cody

Freeware Tools, Games and Humour
http://www.deutronium.de.vu || http://www.deutronium.tk
Nov 16 '05 #3
cody,

No, it does not. However, just because code locks on that particular
type, doesn't mean that code in other sections of the application can't lock
on that same type.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"cody" <no****************@gmx.net> wrote in message
news:uR**************@tk2msftngp13.phx.gbl...
It is possible that there are other areas of the code that are using

the
type of ApplicationLog as the object on which to lock a section of code.
Getting the Type of a class doesn't cause static constructor code to fire (using typeof).

Does that mean that a static ctor could be called more than once?

--
cody

Freeware Tools, Games and Humour
http://www.deutronium.de.vu || http://www.deutronium.tk

Nov 16 '05 #4
> No, it does not. However, just because code locks on that particular
type, doesn't mean that code in other sections of the application can't lock on that same type.


I'd lie if I'd say I understood this. Iam no threading expert could you
please explain this to me?

--
cody

Freeware Tools, Games and Humour
http://www.deutronium.de.vu || http://www.deutronium.tk
Nov 16 '05 #5
cody,

When you use the lock keyword, you need an object reference to use as a
lock. In the static constructor, it is locking on the type that the static
constructor is for (since it is an instance of type Type). Now, this
doesn't mean that some OTHER code can't lock on the same instance of Type.
It doesn't always have to lock around the SAME code.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
"cody" <no****************@gmx.net> wrote in message
news:Od**************@TK2MSFTNGP11.phx.gbl...
No, it does not. However, just because code locks on that particular
type, doesn't mean that code in other sections of the application can't

lock
on that same type.


I'd lie if I'd say I understood this. Iam no threading expert could you
please explain this to me?

--
cody

Freeware Tools, Games and Humour
http://www.deutronium.de.vu || http://www.deutronium.tk

Nov 16 '05 #6
Hi Nicolas,

Thank you for your explanation but there's still something that I don't
understand.
Please listen to the following and point where I make a mistake.

1. Static constructor (SC) is garanteed to be executed not more then once
(isn't it?).
2. If a class contains only static methods (which is the case) SC is
executed (implicite) BEFORE the first call to a static method.
3. That means that SC code cannot interfere (i.e. be executed
simultaneously) with any other static method code.
4. As a result, there's no need to protect execution of SC against
multithreading safety.

Helper question. Is it possible the a static method (let's say in another
thread) starts its execution before the execution of static constructor
ends?

Thanks
Marek

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:uR**************@tk2msftngp13.phx.gbl...
cody,

No, it does not. However, just because code locks on that particular
type, doesn't mean that code in other sections of the application can't lock on that same type.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"cody" <no****************@gmx.net> wrote in message
news:uR**************@tk2msftngp13.phx.gbl...
It is possible that there are other areas of the code that are using
the
type of ApplicationLog as the object on which to lock a section of
code. Getting the Type of a class doesn't cause static constructor code to

fire (using typeof).

Does that mean that a static ctor could be called more than once?

--
cody

Freeware Tools, Games and Humour
http://www.deutronium.de.vu || http://www.deutronium.tk


Nov 16 '05 #7
Marek <ma**************@sbcglobal.net> wrote:
Thank you for your explanation but there's still something that I don't
understand.
Please listen to the following and point where I make a mistake.

1. Static constructor (SC) is garanteed to be executed not more then once
(isn't it?).
Yes, so long as it's not called directly by reflection.
2. If a class contains only static methods (which is the case) SC is
executed (implicite) BEFORE the first call to a static method.
Yes.
3. That means that SC code cannot interfere (i.e. be executed
simultaneously) with any other static method code.
Yes.
4. As a result, there's no need to protect execution of SC against
multithreading safety.
Well, it depends on what that static constructor does. It may call
other methods which aren't thread-safe, and need to acquire the same
locks as other callers of those methods acquire.
Helper question. Is it possible the a static method (let's say in another
thread) starts its execution before the execution of static constructor
ends?


Not usually - there are times where you'd get deadlock otherwise, and
times where it's the thread which is executing the static initializer
which is also executing the static method. For instance:

static Foo()
{
DoSomething();
}

static void DoSomething()
{
}

Clearly DoSomething is called before the static method has completed
here, by definition.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8
Hi Jon:

I was not precise enough in the question 4. Of course, other resources may
have to be protected against concurrent access. I meant that locking on the
type class instance inside the static constructor does not make any sense.
Is that correct?

As far as I have understood your answer to the helper question, CLR provides
some kind of protection against letting other static methods get started
before the static constructor ends its execution. Is that what you said?

Marek

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Marek <ma**************@sbcglobal.net> wrote:
Thank you for your explanation but there's still something that I don't
understand.
Please listen to the following and point where I make a mistake.

1. Static constructor (SC) is garanteed to be executed not more then once (isn't it?).


Yes, so long as it's not called directly by reflection.
2. If a class contains only static methods (which is the case) SC is
executed (implicite) BEFORE the first call to a static method.


Yes.
3. That means that SC code cannot interfere (i.e. be executed
simultaneously) with any other static method code.


Yes.
4. As a result, there's no need to protect execution of SC against
multithreading safety.


Well, it depends on what that static constructor does. It may call
other methods which aren't thread-safe, and need to acquire the same
locks as other callers of those methods acquire.
Helper question. Is it possible the a static method (let's say in another thread) starts its execution before the execution of static constructor
ends?


Not usually - there are times where you'd get deadlock otherwise, and
times where it's the thread which is executing the static initializer
which is also executing the static method. For instance:

static Foo()
{
DoSomething();
}

static void DoSomething()
{
}

Clearly DoSomething is called before the static method has completed
here, by definition.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #9
Marek <ma**************@sbcglobal.net> wrote:
I was not precise enough in the question 4. Of course, other resources may
have to be protected against concurrent access. I meant that locking on the
type class instance inside the static constructor does not make any sense.
Is that correct?
No - because as Nicholas said, other classes may be using the type for
locking as well. The things that the static constructor does may need
to execute separately from anything else which would lock on the type.
As far as I have understood your answer to the helper question, CLR provides
some kind of protection against letting other static methods get started
before the static constructor ends its execution. Is that what you said?


Yes, with some conditions. See section 9.5.3 of partition 1 of the ECMA
spec for more details.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10
Thank you Jon. It's more than clear now.
Marek

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Marek <ma**************@sbcglobal.net> wrote:
I was not precise enough in the question 4. Of course, other resources may have to be protected against concurrent access. I meant that locking on the type class instance inside the static constructor does not make any sense. Is that correct?


No - because as Nicholas said, other classes may be using the type for
locking as well. The things that the static constructor does may need
to execute separately from anything else which would lock on the type.
As far as I have understood your answer to the helper question, CLR provides some kind of protection against letting other static methods get started
before the static constructor ends its execution. Is that what you said?


Yes, with some conditions. See section 9.5.3 of partition 1 of the ECMA
spec for more details.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #11

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

Similar topics

7
by: ank | last post by:
Hi, I was curious about how to define static data member of template class. Should I put the definition in a separate source file or in the same header file as its template class? And when this...
3
by: Kirk Marple | last post by:
Just want to see if this is 'by design' or a bug... I have a common List<T> defined in a base class, and the base class has a static property to expose this list. I wanted the derived class to...
6
by: Marek | last post by:
Hi, I am analyzing Duwamish7 source code boundled with Visual Studio .NET 2003. Could anoybody explain why the Monitor.Enter and Monitor.Exit block is used inside a static constructor? The code...
11
by: Kevin Prichard | last post by:
Hi all, I've recently been following the object-oriented techiques discussed here and have been testing them for use in a web application. There is problem that I'd like to discuss with you...
12
by: Hemanth | last post by:
Hi, I have a base class with a static constructor and some abstract methods. Derived classes implement these methods. From articles on the web, it appears that there is no guarentee that this...
18
by: Zytan | last post by:
I just got a TypeInitializationException exception. Why it is a common cause for this? The InnerException is System.FormatException, although I don't see anything requesting something to be...
9
by: Steven Woody | last post by:
Hi, Supposing a class get a complicated static member foo, and it need to be initialized before any method of the class can be called, where should I put these initialization code? I don't want...
1
by: Angus | last post by:
Hi all I have a design which models a telephone system. Roughly the design has these two items: device class which models an extension on the telephone system. The device constructor takes...
5
by: Dave | last post by:
Hello, Suppose you have a class with a static property with only a get (read only). You also have code in a static constructor that sets these properties but takes 1 hour to run. Now suppose...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.