Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know if this C# method is thread safe?

I'm working on creating a call back function for an ASP.NET cache item removal event.

The documentation says I should call a method on an object or calls I know will exist (will be in scope), such as a static method, but it said I need to ensure the static is thread safe.

Part 1: What are some examples of things I could do to make it un-thread safe?

Part 2: Does this mean that if I have

static int addOne(int someNumber){     int foo = someNumber;     return foo +1;  } 

and I call Class.addOne(5); and Class.addOne(6); simutaneously, Might I get 6 or 7 returned depending on who which invocation sets foo first? (i.e. a race condition)

like image 650
MatthewMartin Avatar asked Jan 07 '09 16:01

MatthewMartin


People also ask

What is if condition in C?

C has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.

What does if 1 mean in C?

The boolean operators function in a similar way to the comparison operators: each returns 0 if evaluates to FALSE or 1 if it evaluates to TRUE.

What is if statement in C with example?

The statement inside the if block are executed only when condition is true, otherwise not. If we want to execute only one statement when condition is true, then braces ({}) can be removed. In general, we should not omit the braces even if, there is a single statement to execute.


1 Answers

That addOne function is indeed thread safe because it doesn't access any data that could be accessed by another thread. Local variables cannot be shared among threads because each thread gets its own stack. You do have to make sure, however, that the function parameters are value types and not reference types.

static void MyFunction(int x) { ... } // thread safe. The int is copied onto the local stack.  static void MyFunction(Object o) { ... } // Not thread safe. Since o is a reference type, it might be shared among multiple threads.  
like image 86
Cybis Avatar answered Sep 28 '22 11:09

Cybis