views:

194

answers:

4

In .NET how can I know if a class or method is thread safe or not? Is it by default not thread safe?

+6  A: 

This is no attribute for this: you have to read the documentation for each item your are interested in. You can't make something thread safe simply by adding an attribute to it. That's like taking an orange and putting a sticker on it that says, "Apple".

Of course, the same thing is true for serialization and it didn't stop them there, but still: no attribute. Read the docs.

Joel Coehoorn
All static methods and properties are assumed to be thread safe by default (i.e. unless documented otherwise), for instance methods the assumption is that they are not.
Richard
Assuming a method is not thread safe when it is causes no harm, assuming one is thread safe when its not can be nasty. Your better off to assume nothing is thread safe unless indicated.
JoshBerke
+1  A: 

I got my back on Joel Coehoorn on this one, would be easy to 'fake' such claims.

Why not add the threadsafe text in the function description

PoweRoy
I wouldn't worry so much about 'faking' it. But concurrency is hard: it would be very likely that a bug has slipped through and that attribute is just incorrect.
Joel Coehoorn
But if the attribute is incorrect, it's likely that the documentation (if any) would be just as incorrect.
Jim Mischel
A: 

There is no use case scenario of making a class synchronized, as far as method is concerned you use following coding style:

using System.Runtime.CompilerServices;
[MethodImpl(MethodImplOptions.Synchronized)]   
void MyMethod()   
{   
DoSomething();   
}
Rutesh Makhijani
The problem is; that still doesn't imply that the method is thread-safe -because another thread could be calling a different method that *doesn't* have the [MethodImpl], thus trashing each-other. Likewise even if all fields are readonly, fields on child objects could be mutable, and cause problems.
Marc Gravell
+1  A: 

It is possible to make all access to your object serial via IContributeObjectSink/IContextAttribute although this will suffer from a large performance hit since it will require your object to subclass MarshalByRefObject,context creation overhead, etc...

Matt Davison