Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an attribute to mark the class or method to be thread safe in .NET?

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

like image 916
Ahmed Avatar asked Mar 18 '09 12:03

Ahmed


2 Answers

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.

like image 160
Joel Coehoorn Avatar answered Sep 22 '22 19:09

Joel Coehoorn


No, and it would be pointless.

Let's assume I have a thread safe List, it has three Thread Safe™ methods:

void Add( something);
void Remove(index);
int GetCount();
something GetElementAt(index);

Thread one:

for 1 to 100 do
 list.Add(12);

Thread two and three:

while( list.GetCount() >0)
{
    list.Remove(0);
}

The code above will crash (sooner or later) because the list might change between the time you call GetCount and Remove

like image 42
AK_ Avatar answered Sep 23 '22 19:09

AK_