473,407 Members | 2,598 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,407 software developers and data experts.

Is this thread safe?


I know that XslTransform's Transform is thread safe according to the MSDN,
and that Load is not. I've therefore applied this simply Mutex to it and
would just like to confirm this is okay.
XslTransform xslt = null;
Mutex mut = new Mutex();

public override string MapMessage ( string messageSource )
{

//
// create and load up a new transform if required

if ( xslt == null )
{
if ( File.Exists(configFile) )
{
mut.WaitOne();

xslt = new XslTransform();
xslt.Load( configFile );

mut.ReleaseMutex();
}
else
{
throw ( new ApplicationException ( "Configuration error,
XSL file does not exist. " + configFile ) );
}
}

//
// rest of the function code here

}
Nov 16 '05 #1
24 1775
I know that is wrong! Just realised the problem it could give me...
What about this?
XslTransform xslt = null;
Mutex mut = new Mutex();

public override string MapMessage ( string messageSource )
{

//
// create and load up a new transform if required

mut.WaitOne();

if ( xslt == null )
{
if ( File.Exists(configFile) )
{

xslt = new XslTransform();
xslt.Load( configFile );

}
else
{
mut.ReleaseMutex();
throw ( new ApplicationException ( "Configuration error,
XSL file does not exist. " + configFile ) );
}
}

mut.ReleaseMutex();

//
// rest of the function code here

}

"Dan Bass" <danielbass [at] postmaster [dot] co [dot] uk> wrote in message
news:eT**************@TK2MSFTNGP14.phx.gbl...

I know that XslTransform's Transform is thread safe according to the MSDN,
and that Load is not. I've therefore applied this simply Mutex to it and
would just like to confirm this is okay.
XslTransform xslt = null;
Mutex mut = new Mutex();

public override string MapMessage ( string messageSource )
{

//
// create and load up a new transform if required

if ( xslt == null )
{
if ( File.Exists(configFile) )
{
mut.WaitOne();

xslt = new XslTransform();
xslt.Load( configFile );

mut.ReleaseMutex();
}
else
{
throw ( new ApplicationException ( "Configuration
error, XSL file does not exist. " + configFile ) );
}
}

//
// rest of the function code here

}

Nov 16 '05 #2
Dan,

I wouldn't use a Mutex. I would just make the method synchronized, like
so:

[MethodImpl(MethodImplOptions.Synchronized)]
public override string MapMessage ( string messageSource )
{
// create and load up a new transform if required
mut.WaitOne();

if ( xslt == null )
{
if ( File.Exists(configFile) )
{
xslt = new XslTransform();
xslt.Load( configFile );
}
}
else
{
throw ( new ApplicationException ( "Configuration error, XSL file
does not exist. " + configFile));
}

// rest of the function code here
}

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

"Dan Bass" <danielbass [at] postmaster [dot] co [dot] uk> wrote in message
news:%2****************@TK2MSFTNGP12.phx.gbl...
I know that is wrong! Just realised the problem it could give me...
What about this?
XslTransform xslt = null;
Mutex mut = new Mutex();

public override string MapMessage ( string messageSource )
{

//
// create and load up a new transform if required

mut.WaitOne();

if ( xslt == null )
{
if ( File.Exists(configFile) )
{

xslt = new XslTransform();
xslt.Load( configFile );

}
else
{
mut.ReleaseMutex();
throw ( new ApplicationException ( "Configuration
error, XSL file does not exist. " + configFile ) );
}
}

mut.ReleaseMutex();

//
// rest of the function code here

}

"Dan Bass" <danielbass [at] postmaster [dot] co [dot] uk> wrote in message
news:eT**************@TK2MSFTNGP14.phx.gbl...

I know that XslTransform's Transform is thread safe according to the
MSDN, and that Load is not. I've therefore applied this simply Mutex to
it and would just like to confirm this is okay.
XslTransform xslt = null;
Mutex mut = new Mutex();

public override string MapMessage ( string messageSource )
{

//
// create and load up a new transform if required

if ( xslt == null )
{
if ( File.Exists(configFile) )
{
mut.WaitOne();

xslt = new XslTransform();
xslt.Load( configFile );

mut.ReleaseMutex();
}
else
{
throw ( new ApplicationException ( "Configuration
error, XSL file does not exist. " + configFile ) );
}
}

//
// rest of the function code here

}


Nov 16 '05 #3
Hi Dan,
I wouldn't use a Mutex. I would recommend using Monitor. There area couple
options. The most common is to use the C# lock statement, but this has some
drawbacks. Most notably, it is equivalent to a Monitor.TryEnter with an
infinite timeout. Therefore, a lot of the smart guys recommend using
Monitor.TryEnter with a finite timeout instead.

You may want to check out the articles and utility library by Jon Skeet at:
http://www.yoda.arachsys.com/csharp/...ernative.shtml

and a related blog article by Ian G at:
http://www.interact-sw.co.uk/iangblo...retimedlocking
http://www.interact-sw.co.uk/iangblo.../03/23/locking

Also, if you code this on your own using Monitor.TryEnter, make sure you
start a try block immediately after you get the monitor and then exit the
monitor in a finally block.

The links above will give you full details on this and even some ready to
use code.

Regards,
Mountain

"Dan Bass" <danielbass [at] postmaster [dot] co [dot] uk> wrote in message
news:%2****************@TK2MSFTNGP12.phx.gbl...
I know that is wrong! Just realised the problem it could give me...
What about this?
XslTransform xslt = null;
Mutex mut = new Mutex();

public override string MapMessage ( string messageSource )
{

//
// create and load up a new transform if required

mut.WaitOne();

if ( xslt == null )
{
if ( File.Exists(configFile) )
{

xslt = new XslTransform();
xslt.Load( configFile );

}
else
{
mut.ReleaseMutex();
throw ( new ApplicationException ( "Configuration error, XSL file does not exist. " + configFile ) );
}
}

mut.ReleaseMutex();

//
// rest of the function code here

}

"Dan Bass" <danielbass [at] postmaster [dot] co [dot] uk> wrote in message
news:eT**************@TK2MSFTNGP14.phx.gbl...

I know that XslTransform's Transform is thread safe according to the MSDN, and that Load is not. I've therefore applied this simply Mutex to it and
would just like to confirm this is okay.
XslTransform xslt = null;
Mutex mut = new Mutex();

public override string MapMessage ( string messageSource )
{

//
// create and load up a new transform if required

if ( xslt == null )
{
if ( File.Exists(configFile) )
{
mut.WaitOne();

xslt = new XslTransform();
xslt.Load( configFile );

mut.ReleaseMutex();
}
else
{
throw ( new ApplicationException ( "Configuration
error, XSL file does not exist. " + configFile ) );
}
}

//
// rest of the function code here

}


Nov 16 '05 #4
Hi Nicholas,
If I understand correctly, using the MethodImpl attribute is the same as a
lock on 'this'.

Locking on 'this' isn't recommended according to an excellent article by
Jeffrey Richter at http://msdn.microsoft.com/msdnmag/issues/03/01/NET/

Jon Skeet also makes some excellent points about what to lock on at
http://www.yoda.arachsys.com/csharp/...ckchoice.shtml

Bottom line: create a private variable to lock on and use it only for
synchronization purposes.

Regards,
Mountain

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

I wouldn't use a Mutex. I would just make the method synchronized, like so:

[MethodImpl(MethodImplOptions.Synchronized)]
public override string MapMessage ( string messageSource )
{
// create and load up a new transform if required
mut.WaitOne();

if ( xslt == null )
{
if ( File.Exists(configFile) )
{
xslt = new XslTransform();
xslt.Load( configFile );
}
}
else
{
throw ( new ApplicationException ( "Configuration error, XSL file
does not exist. " + configFile));
}

// rest of the function code here
}

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

"Dan Bass" <danielbass [at] postmaster [dot] co [dot] uk> wrote in message
news:%2****************@TK2MSFTNGP12.phx.gbl...
I know that is wrong! Just realised the problem it could give me...
What about this?
XslTransform xslt = null;
Mutex mut = new Mutex();

public override string MapMessage ( string messageSource )
{

//
// create and load up a new transform if required

mut.WaitOne();

if ( xslt == null )
{
if ( File.Exists(configFile) )
{

xslt = new XslTransform();
xslt.Load( configFile );

}
else
{
mut.ReleaseMutex();
throw ( new ApplicationException ( "Configuration
error, XSL file does not exist. " + configFile ) );
}
}

mut.ReleaseMutex();

//
// rest of the function code here

}

"Dan Bass" <danielbass [at] postmaster [dot] co [dot] uk> wrote in message news:eT**************@TK2MSFTNGP14.phx.gbl...

I know that XslTransform's Transform is thread safe according to the
MSDN, and that Load is not. I've therefore applied this simply Mutex to
it and would just like to confirm this is okay.
XslTransform xslt = null;
Mutex mut = new Mutex();

public override string MapMessage ( string messageSource )
{

//
// create and load up a new transform if required

if ( xslt == null )
{
if ( File.Exists(configFile) )
{
mut.WaitOne();

xslt = new XslTransform();
xslt.Load( configFile );

mut.ReleaseMutex();
}
else
{
throw ( new ApplicationException ( "Configuration
error, XSL file does not exist. " + configFile ) );
}
}

//
// rest of the function code here

}



Nov 16 '05 #5
I've read Richter's article, and I think that the security concerns
don't hold much weight, to be honest. If it got to the point where
malicious code could run on your machine, then whether or not you expose the
lock your objects use (namely, this), doesn't matter. The malicious code
could simply perform a DoS attack using:

while (true);

Now the argument that you only want to lock on a subset of the members
of your class holds more weight, but the counterpoint to that is that with
proper design (where you don't have super sized classes), your operations
will affect the whole class anyways (because they will not be loaded
tremendously with properties and expand the scope of the class by too much).

Also, with reflection, it's almost impossible to truly keep someone from
accessing your locks. You could remove permissions for reflection from the
class, I believe, but then you are hindering yourself in other ways. You
have to decide where to trade off.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Mr. Mountain" <mt*****@mediaone.net> wrote in message
news:fBlwd.271781$R05.178168@attbi_s53...
Hi Nicholas,
If I understand correctly, using the MethodImpl attribute is the same as a
lock on 'this'.

Locking on 'this' isn't recommended according to an excellent article by
Jeffrey Richter at http://msdn.microsoft.com/msdnmag/issues/03/01/NET/

Jon Skeet also makes some excellent points about what to lock on at
http://www.yoda.arachsys.com/csharp/...ckchoice.shtml

Bottom line: create a private variable to lock on and use it only for
synchronization purposes.

Regards,
Mountain

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

I wouldn't use a Mutex. I would just make the method synchronized,

like
so:

[MethodImpl(MethodImplOptions.Synchronized)]
public override string MapMessage ( string messageSource )
{
// create and load up a new transform if required
mut.WaitOne();

if ( xslt == null )
{
if ( File.Exists(configFile) )
{
xslt = new XslTransform();
xslt.Load( configFile );
}
}
else
{
throw ( new ApplicationException ( "Configuration error, XSL file
does not exist. " + configFile));
}

// rest of the function code here
}

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

"Dan Bass" <danielbass [at] postmaster [dot] co [dot] uk> wrote in
message
news:%2****************@TK2MSFTNGP12.phx.gbl...
>I know that is wrong! Just realised the problem it could give me...
> What about this?
>
>
> XslTransform xslt = null;
> Mutex mut = new Mutex();
>
> public override string MapMessage ( string messageSource )
> {
>
> //
> // create and load up a new transform if required
>
> mut.WaitOne();
>
> if ( xslt == null )
> {
> if ( File.Exists(configFile) )
> {
>
> xslt = new XslTransform();
> xslt.Load( configFile );
>
> }
> else
> {
> mut.ReleaseMutex();
> throw ( new ApplicationException ( "Configuration
> error, XSL file does not exist. " + configFile ) );
> }
> }
>
> mut.ReleaseMutex();
>
> //
> // rest of the function code here
>
> }
>
> "Dan Bass" <danielbass [at] postmaster [dot] co [dot] uk> wrote in message > news:eT**************@TK2MSFTNGP14.phx.gbl...
>>
>> I know that XslTransform's Transform is thread safe according to the
>> MSDN, and that Load is not. I've therefore applied this simply Mutex
>> to
>> it and would just like to confirm this is okay.
>>
>>
>> XslTransform xslt = null;
>> Mutex mut = new Mutex();
>>
>> public override string MapMessage ( string messageSource )
>> {
>>
>> //
>> // create and load up a new transform if required
>>
>> if ( xslt == null )
>> {
>> if ( File.Exists(configFile) )
>> {
>> mut.WaitOne();
>>
>> xslt = new XslTransform();
>> xslt.Load( configFile );
>>
>> mut.ReleaseMutex();
>> }
>> else
>> {
>> throw ( new ApplicationException ( "Configuration
>> error, XSL file does not exist. " + configFile ) );
>> }
>> }
>>
>> //
>> // rest of the function code here
>>
>> }
>>
>>
>
>



Nov 16 '05 #6
Dan Bass wrote:
XslTransform xslt = null;
Mutex mut = new Mutex(); .... public override string MapMessage ( string messageSource )
{
mut.WaitOne(); ....
mut.ReleaseMutex();
}
You should at least be exception defensive here, using

mut.WaitOne();
try {
...
} finally {
mut.ReleaseMutex();
}

As pointed out other places in this thread, using "lock()" would
probably be preferred to the above:
public override string MapMessage ( string messageSource )
{ lock(someObj) {
....
} }


Especially since it's less error-prone, and it's very easy to read.

Whether you should lock on "this" or another object, I will leave for a
separate discussion :)

--
Helge
Nov 16 '05 #7
You didn't mention one of the most important drawbacks of using lock -- if
the monitor is unavailable, it will block indefinitely (infinite timeout).
I agree with Ian G that production code shouldn't have a "feature" like
this. It seems far better to use Monitor.TryEnter, (or Ian's or Jon Skeet's
code that makes using Monitor.TryEnter as easy as using lock)
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:%2****************@TK2MSFTNGP12.phx.gbl...
I've read Richter's article, and I think that the security concerns
don't hold much weight, to be honest. If it got to the point where
malicious code could run on your machine, then whether or not you expose the lock your objects use (namely, this), doesn't matter. The malicious code
could simply perform a DoS attack using:

while (true);

Now the argument that you only want to lock on a subset of the members
of your class holds more weight, but the counterpoint to that is that with
proper design (where you don't have super sized classes), your operations
will affect the whole class anyways (because they will not be loaded
tremendously with properties and expand the scope of the class by too much).
Also, with reflection, it's almost impossible to truly keep someone from accessing your locks. You could remove permissions for reflection from the class, I believe, but then you are hindering yourself in other ways. You
have to decide where to trade off.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Mr. Mountain" <mt*****@mediaone.net> wrote in message
news:fBlwd.271781$R05.178168@attbi_s53...
Hi Nicholas,
If I understand correctly, using the MethodImpl attribute is the same as a lock on 'this'.

Locking on 'this' isn't recommended according to an excellent article by
Jeffrey Richter at http://msdn.microsoft.com/msdnmag/issues/03/01/NET/

Jon Skeet also makes some excellent points about what to lock on at
http://www.yoda.arachsys.com/csharp/...ckchoice.shtml

Bottom line: create a private variable to lock on and use it only for
synchronization purposes.

Regards,
Mountain

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

I wouldn't use a Mutex. I would just make the method synchronized,

like
so:

[MethodImpl(MethodImplOptions.Synchronized)]
public override string MapMessage ( string messageSource )
{
// create and load up a new transform if required
mut.WaitOne();

if ( xslt == null )
{
if ( File.Exists(configFile) )
{
xslt = new XslTransform();
xslt.Load( configFile );
}
}
else
{
throw ( new ApplicationException ( "Configuration error, XSL file does not exist. " + configFile));
}

// rest of the function code here
}

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

"Dan Bass" <danielbass [at] postmaster [dot] co [dot] uk> wrote in
message
news:%2****************@TK2MSFTNGP12.phx.gbl...
>I know that is wrong! Just realised the problem it could give me...
> What about this?
>
>
> XslTransform xslt = null;
> Mutex mut = new Mutex();
>
> public override string MapMessage ( string messageSource )
> {
>
> //
> // create and load up a new transform if required
>
> mut.WaitOne();
>
> if ( xslt == null )
> {
> if ( File.Exists(configFile) )
> {
>
> xslt = new XslTransform();
> xslt.Load( configFile );
>
> }
> else
> {
> mut.ReleaseMutex();
> throw ( new ApplicationException ( "Configuration
> error, XSL file does not exist. " + configFile ) );
> }
> }
>
> mut.ReleaseMutex();
>
> //
> // rest of the function code here
>
> }
>
> "Dan Bass" <danielbass [at] postmaster [dot] co [dot] uk> wrote in

message
> news:eT**************@TK2MSFTNGP14.phx.gbl...
>>
>> I know that XslTransform's Transform is thread safe according to the
>> MSDN, and that Load is not. I've therefore applied this simply Mutex
>> to
>> it and would just like to confirm this is okay.
>>
>>
>> XslTransform xslt = null;
>> Mutex mut = new Mutex();
>>
>> public override string MapMessage ( string messageSource )
>> {
>>
>> //
>> // create and load up a new transform if required
>>
>> if ( xslt == null )
>> {
>> if ( File.Exists(configFile) )
>> {
>> mut.WaitOne();
>>
>> xslt = new XslTransform();
>> xslt.Load( configFile );
>>
>> mut.ReleaseMutex();
>> }
>> else
>> {
>> throw ( new ApplicationException ( "Configuration
>> error, XSL file does not exist. " + configFile ) );
>> }
>> }
>>
>> //
>> // rest of the function code here
>>
>> }
>>
>>
>
>



Nov 16 '05 #8
Nicholas Paldino [.NET/C# MVP] <mv*@spam.guard.caspershouse.com> wrote:
I've read Richter's article, and I think that the security concerns
don't hold much weight, to be honest. If it got to the point where
malicious code could run on your machine, then whether or not you expose the
lock your objects use (namely, this), doesn't matter. The malicious code
could simply perform a DoS attack using:

while (true);


I don't think it's really a security matter. (The word 'security'
doesn't appear in Richter's article or mine.) For me, it's a matter of
making sure that no-one's code (including my own) will *accidentally*
end up locking on something that another bit of code thinks it's
locking on exclusively.

Using private locks makes the code more readable and more maintainable
- IMO, of course.

--
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
> Bottom line: create a private variable to lock on and use it only for
synchronization purposes.


Thanks for all the responses so far.

Oky, hoolllllld on a minute, threading novice here! What's wrong with Mutex?
Nov 16 '05 #10
Reading through your threading pages... going way over this head and feeling
really stupid right now! ;o)
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Nicholas Paldino [.NET/C# MVP] <mv*@spam.guard.caspershouse.com> wrote:
I've read Richter's article, and I think that the security concerns
don't hold much weight, to be honest. If it got to the point where
malicious code could run on your machine, then whether or not you expose
the
lock your objects use (namely, this), doesn't matter. The malicious code
could simply perform a DoS attack using:

while (true);


I don't think it's really a security matter. (The word 'security'
doesn't appear in Richter's article or mine.) For me, it's a matter of
making sure that no-one's code (including my own) will *accidentally*
end up locking on something that another bit of code thinks it's
locking on exclusively.

Using private locks makes the code more readable and more maintainable
- IMO, of course.

--
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
Is this better?
readonly object xsltLock = new object();
XslTransform xslt = null;

public override string MapMessage ( string messageSource )
{
//
// create and load up a new transform if required

lock ( xsltLock )
{
if ( xslt == null )
{
if ( File.Exists(configFile) )
{
xslt = new XslTransform();
xslt.Load( configFile );
}
else
{
// will lock release on this?
throw ( new ApplicationException ( "Configuration
error, XSL file does not exist. " + configFile ) );
}
}
}

//
// rest of the method

}
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Nicholas Paldino [.NET/C# MVP] <mv*@spam.guard.caspershouse.com> wrote:
I've read Richter's article, and I think that the security concerns
don't hold much weight, to be honest. If it got to the point where
malicious code could run on your machine, then whether or not you expose
the
lock your objects use (namely, this), doesn't matter. The malicious code
could simply perform a DoS attack using:

while (true);


I don't think it's really a security matter. (The word 'security'
doesn't appear in Richter's article or mine.) For me, it's a matter of
making sure that no-one's code (including my own) will *accidentally*
end up locking on something that another bit of code thinks it's
locking on exclusively.

Using private locks makes the code more readable and more maintainable
- IMO, of course.

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

Nov 16 '05 #12
Looks good; the lock keyword guarantees that the lock will be released
regardless of how control leaves the lock region, so the xlstLock will be
released even if you throw an exception. The issue of whether you should
throw an exception if the file is missing, or what type of exception to
throw, is an issue separate from best practices regarding locks.

"Dan Bass" <danielbass [at] postmaster [dot] co [dot] uk> wrote in message
news:ul**************@TK2MSFTNGP14.phx.gbl...
Is this better?
readonly object xsltLock = new object();
XslTransform xslt = null;

public override string MapMessage ( string messageSource )
{
//
// create and load up a new transform if required

lock ( xsltLock )
{
if ( xslt == null )
{
if ( File.Exists(configFile) )
{
xslt = new XslTransform();
xslt.Load( configFile );
}
else
{
// will lock release on this?
throw ( new ApplicationException ( "Configuration
error, XSL file does not exist. " + configFile ) );
}
}
}

//
// rest of the method

}
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Nicholas Paldino [.NET/C# MVP] <mv*@spam.guard.caspershouse.com> wrote:
I've read Richter's article, and I think that the security concerns
don't hold much weight, to be honest. If it got to the point where
malicious code could run on your machine, then whether or not you expose
the
lock your objects use (namely, this), doesn't matter. The malicious
code
could simply perform a DoS attack using:

while (true);


I don't think it's really a security matter. (The word 'security'
doesn't appear in Richter's article or mine.) For me, it's a matter of
making sure that no-one's code (including my own) will *accidentally*
end up locking on something that another bit of code thinks it's
locking on exclusively.

Using private locks makes the code more readable and more maintainable
- IMO, of course.

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


Nov 16 '05 #13

David,

Thanks for the feedback.

The Exception is there because the module in which this code exists cannot
function without the presence of the XSL file in question. The desire is to
the catch this exception at a higher level, then log the details alerting
the user of this incident. The application is a windows service using a
plug-in archtecture. This code belongs to one such plug-in.

I assumed it would be an ApplicationException simlpy because it's a general
error thrown by the application code.

Is my thinking correct on these issues?

"David Levine" <no****************@wi.rr.com> wrote in message
news:%2****************@TK2MSFTNGP11.phx.gbl...
Looks good; the lock keyword guarantees that the lock will be released
regardless of how control leaves the lock region, so the xlstLock will be
released even if you throw an exception. The issue of whether you should
throw an exception if the file is missing, or what type of exception to
throw, is an issue separate from best practices regarding locks.

"Dan Bass" <danielbass [at] postmaster [dot] co [dot] uk> wrote in message
news:ul**************@TK2MSFTNGP14.phx.gbl...
Is this better?
readonly object xsltLock = new object();
XslTransform xslt = null;

public override string MapMessage ( string messageSource )
{
//
// create and load up a new transform if required

lock ( xsltLock )
{
if ( xslt == null )
{
if ( File.Exists(configFile) )
{
xslt = new XslTransform();
xslt.Load( configFile );
}
else
{
// will lock release on this?
throw ( new ApplicationException ( "Configuration
error, XSL file does not exist. " + configFile ) );
}
}
}

//
// rest of the method

}
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Nicholas Paldino [.NET/C# MVP] <mv*@spam.guard.caspershouse.com> wrote:
I've read Richter's article, and I think that the security concerns
don't hold much weight, to be honest. If it got to the point where
malicious code could run on your machine, then whether or not you
expose the
lock your objects use (namely, this), doesn't matter. The malicious
code
could simply perform a DoS attack using:

while (true);

I don't think it's really a security matter. (The word 'security'
doesn't appear in Richter's article or mine.) For me, it's a matter of
making sure that no-one's code (including my own) will *accidentally*
end up locking on something that another bit of code thinks it's
locking on exclusively.

Using private locks makes the code more readable and more maintainable
- IMO, of course.

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



Nov 16 '05 #14

"Dan Bass" <danielbass [at] postmaster [dot] co [dot] uk> wrote in message
news:eu*************@TK2MSFTNGP09.phx.gbl...

David,

Thanks for the feedback.

The Exception is there because the module in which this code exists cannot
function without the presence of the XSL file in question. The desire is
to the catch this exception at a higher level, then log the details
alerting the user of this incident. The application is a windows service
using a plug-in archtecture. This code belongs to one such plug-in.

I assumed it would be an ApplicationException simlpy because it's a
general error thrown by the application code.

Is my thinking correct on these issues?


This appears to be a case where throwing is the correct course of action.

There is no clear agreement on what exception type ought to be thrown. If
there is a programmatic action that a caller can take to recover from the
exception then creating a custom exception type is useful - the caller can
then catch that specific type and take corrective action. If there is no
clearly defined recovery mechanism then using a generic exception is the
preferred method.

The latest guidelines suggest that using ApplicationException is to be
discouraged as the value-add is small, but if there is no predefined
exception type that is suitable then the other option is to simply throw the
base Exception type. I have no yet reached a conclusion as to which I
prefer, although for simplicity I typically use the base Exception class.

Nov 16 '05 #15
> The latest guidelines suggest that using ApplicationException is to be
discouraged as the value-add is small, but if there is no predefined
exception type that is suitable then the other option is to simply throw
the base Exception type. I have no yet reached a conclusion as to which I
prefer, although for simplicity I typically use the base Exception class.


I used to too, but then tried a trial of devAdvantage said they should
rather be ApplicationException! I'm not too fussed really because the result
isn't too different in terms of performance or readability.

Nov 16 '05 #16
<"Dan Bass" <danielbass [at] postmaster [dot] co [dot] uk>> wrote:
Bottom line: create a private variable to lock on and use it only for
synchronization purposes.


Thanks for all the responses so far.

Oky, hoolllllld on a minute, threading novice here! What's wrong with
Mutex?


1) It's inefficient compared with monitors - mutexes are much heavier
than monitors, and aren't as well understood by the CLR, so it can't
optimise around them.

2) It doesn't have language support, so it's harder to use.

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

if i'm using the lock(localObject) mechanism, will that lock it from other
processes running as well, or just threads within the same process?

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
<"Dan Bass" <danielbass [at] postmaster [dot] co [dot] uk>> wrote:
> Bottom line: create a private variable to lock on and use it only for
> synchronization purposes.


Thanks for all the responses so far.

Oky, hoolllllld on a minute, threading novice here! What's wrong with
Mutex?


1) It's inefficient compared with monitors - mutexes are much heavier
than monitors, and aren't as well understood by the CLR, so it can't
optimise around them.

2) It doesn't have language support, so it's harder to use.

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

Nov 16 '05 #18
Nope, Monitors are AppDomain specific.If you want to perform cross AppDomain (including cross process) you will need to use Mutexes, Events and other such kernel objects

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

if i'm using the lock(localObject) mechanism, will that lock it from other
processes running as well, or just threads within the same process?

Nov 16 '05 #19

"Richard Blewett [DevelopMentor]" <ri******@NOSPAMdevelop.com> wrote in
message news:ez**************@TK2MSFTNGP12.phx.gbl...
Nope, Monitors are AppDomain specific.If you want to perform cross
AppDomain (including cross process) you will need to use Mutexes, Events
and other such kernel objects

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

if i'm using the lock(localObject) mechanism, will that lock it from
other
processes running as well, or just threads within the same process?


Richard,

IMO Monitors themselves are not Domain "specific", all depends on the type
you are taking a lock on. If you take a lock on a domain neutral type, you
will get a cross-domain lock, else you get a domain specific lock.

Willy.
Nov 16 '05 #20
OK, yes I forgot about domain neutral loaded assemblies - after playing with this for a while to make sure I wasn't smoking ;-) it only works for the type object and any reference type static members for a type in a domain neutral assembly though. Instances of domain neutral types are not themselves domain neutral.

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk
"Richard Blewett [DevelopMentor]" <ri******@NOSPAMdevelop.com> wrote in
message news:ez**************@TK2MSFTNGP12.phx.gbl...
Nope, Monitors are AppDomain specific.If you want to perform cross
AppDomain (including cross process) you will need to use Mutexes, Events
and other such kernel objects


Richard,

IMO Monitors themselves are not Domain "specific", all depends on the type
you are taking a lock on. If you take a lock on a domain neutral type, you
will get a cross-domain lock, else you get a domain specific lock.

Willy.
Nov 16 '05 #21
Actually just rechecked something and static members don't appear to work. I was using Environment.NewLine as a ref type to lock which did work. But then after some thought I realised this is simply an interned string being returned so it proves only that interned strings work. However, if I switch to Environment.OSVersion which is a demand allocated reference type, I get no synchronization.

My blog post about this is here

http://www.dotnetconsult.co.uk/weblo...1-79704555d2b4

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

OK, yes I forgot about domain neutral loaded assemblies - after playing with this for a while to make sure I wasn't smoking ;-) it only works for the type object and any reference type static members for a type in a domain neutral assembly though. Instances of domain neutral types are not themselves domain neutral.

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk
"Richard Blewett [DevelopMentor]" <ri******@NOSPAMdevelop.com> wrote in
message news:ez**************@TK2MSFTNGP12.phx.gbl...
Nope, Monitors are AppDomain specific.If you want to perform cross
AppDomain (including cross process) you will need to use Mutexes, Events
and other such kernel objects


Richard,

IMO Monitors themselves are not Domain "specific", all depends on the type
you are taking a lock on. If you take a lock on a domain neutral type, you
will get a cross-domain lock, else you get a domain specific lock.

Willy.
Nov 16 '05 #22
Richard Blewett [DevelopMentor] <ri******@NOSPAMdevelop.com> wrote:
Actually just rechecked something and static members don't appear to
work. I was using Environment.NewLine as a ref type to lock which did
work. But then after some thought I realised this is simply an
interned string being returned so it proves only that interned
strings work. However, if I switch to Environment.OSVersion which is
a demand allocated reference type, I get no synchronization.


There's one more test, however: test with a MarshalByRefObject, eg
Pens.Black.

I would have tried this with your test code, but it blew up with a
SerializationException for me (as posted).

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

"Richard Blewett [DevelopMentor]" <ri******@NOSPAMdevelop.com> wrote in
message news:e4**************@TK2MSFTNGP10.phx.gbl...
Actually just rechecked something and static members don't appear to work.
I was using Environment.NewLine as a ref type to lock which did work. But
then after some thought I realised this is simply an interned string being
returned so it proves only that interned strings work. However, if I
switch to Environment.OSVersion which is a demand allocated reference
type, I get no synchronization.

My blog post about this is here

http://www.dotnetconsult.co.uk/weblo...1-79704555d2b4

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk


Richard,

We have to make a clear distinction between:
1 - domain-neutral assemblies and how they are shared between application
domains and
2 - object instances and how they are allowed to cross application domains
boundaries.

Say you have two application domains that use the typeof operator to get the
System.Type object for a type that was loaded from a domain-neutral
assembly, here typeof will return a direct reference to a single type and
you'll get cross-application domain synchronization when putting a lock on
it .

object o = typeof(string); // System.String is loaded from a domain-neutral
assembly mscorlib.dll

as used in the sample you posted [1] is a perfect sample, and that is what I
was referring to in my previous post.
Note that it doesn't matter if the reference is a static or an instance
field, static fields are always per-application domain (except RVA
static's), it's the type it references that matters (see later).

Object instances however, are only allowed to be shared between application
domains, when they:
- are of a type loaded as domain-neutral and
- when they marshal-by-bleed or marshal as identity-preserving by-value.

For instance if you make o a string reference;
static string o = "a string";
you will end with two static references directly pointing to the single
instance string (marshal-by-bleed) and get cross-domain synchronization when
locking the instance.
The only other type (AFAIK) that is allowed to marshal-by-bleed is the
System.Threading.Thread.
That's why Environment.OSVersion doesn't "synchronize", it is not a
System.String nor a System.Threaing.Thread type so it doesn't
marshal-by-bleed.
Willy.




Nov 16 '05 #24
Thanks for the clarification Willy. I'd heard of marshal-by-bleed, it always sounded horrbly painful and I never dug into it ;-) but i know what it is. I'd never heard of "marshal as identity-preserving by-value", do you have any more info or a link to details?

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Object instances however, are only allowed to be shared between application
domains, when they:
- are of a type loaded as domain-neutral and
- when they marshal-by-bleed or marshal as identity-preserving by-value.

Nov 16 '05 #25

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

Similar topics

5
by: Roman Suzi | last post by:
(this is a repost with an addition - probably noone noticed my message first time) Hi! Just to be sure, is email package of Python 2.3 thread-safe or not (to use, for example, in...
0
by: Steven Brown | last post by:
I'm trying to figure out how to safely use .NET events/delegates in a thread-safe class. There are a couple problems. One is that the standard "if(EventName != null) EventName(...);" call can...
5
by: nicolas_riesch | last post by:
Does someone know if the module pytz (http://sourceforge.net/projects/pytz/) is thread-safe ? I have not seen it explicitely stated, and just wanted to be sure, as I want to use it. That's...
1
by: Frank Rizzo | last post by:
Some of the classes in the framework are marked as thread-safe in the documentation. In particular the docs say the following: "Any public static (*Shared* in Visual Basic) members of this type...
11
by: dee | last post by:
OleDbCommand class like many .NET classes has the following description in its help file: "Thread Safety Any public static (Shared in Visual Basic) members of this type are safe for...
3
by: tcomer | last post by:
Hello! I'm working on an asynchronous network application that uses multiple threads to do it's work. I have a ChatClient class that handles the basic functionality of connecting to a server and...
15
by: Laser Lu | last post by:
I was often noted by Thread Safety declarations when I was reading .NET Framework Class Library documents in MSDN. The declaration is usually described as 'Any public static (Shared in Visual...
1
by: jecheney | last post by:
Hi, Im currently using the following code for reading/writing to a network socket. private StreamReader clientStreamReader; private StreamWriter clientStreamWriter; .... TcpClient tcpClient...
44
by: climber.cui | last post by:
Hi all, Does anyone have experience on the thread-safty issue with malloc()? Some people said this function provided in stdlib.h is not thread- safe, but someone said it is thread safe. Is it...
3
by: =?Utf-8?B?anBhdHJjaWs=?= | last post by:
Don't see any official notice that compiled library dll's loaded in the BIN directory of an asp.net website need to be thread safe, but concurrent visits to the same web site sure bear this out....
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
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...
0
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...

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.