Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I care about thread safe of static int (4 bytes) variable in ASP .NET

I have the feeling that I should not care about thread safe accessing / writing to an

public static int MyVar = 12;

in ASP .NET.

I read/write to this variable from various user threads. Let's suppose this variable will store the numbers of clicks on a certain button/link.

My theory is that no thread can read/write to this variable at the same time. It's just a simple variable of 4 bytes.

I do care about thread safe, but only for refference objects and List instances or other types that take more cycles to read/update.

I am wrong with my presumption ?

EDIT

I understand this depend of my scenario, but wasn't that the point of the question. The question is: it is right that can be written thread safe code with an (static int) variable without using lock keyword ?

It is my problem to write correct code. The answer seems to be: Yes, if you write correct and simple code, and not to much complicated, you can create thread safe functions without the need of lock keyword.

like image 225
Sorin Avatar asked Dec 17 '22 04:12

Sorin


1 Answers

If one thread simply sets the value and another thread reads the value, then a lock is not necessary; the read and write are atomic. But if multiple threads might be updating it and are also reading it to do the update (e.g., increment), then you definitely do need some kind of synchronization. If only one thread is ever going to update it even for an increment, then I would argue that no synchronization is necessary.

Edit (three years later) It might also be desirable to add the volatile keyword to the declaration to ensure that reads of the value always get the latest value (assuming that matters in the application).

like image 123
Mark Wilkins Avatar answered Mar 09 '23 01:03

Mark Wilkins