web analytics

How to implement a thread-safe C# method?

Options

renaudj 2 - 93
@2017-09-28 08:54:09

The following C# method is 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.

public  static int AddOne(int someNumber)

{ 
 int foo = someNumber; 

 return foo++; 
}

You do have to make sure, however, that the function parameters are value types and not reference types.

But the following method is not a thread safe method because it uses a shard static data.

static int foo;
 
public static int AddOne(int someNumber)
{ 

  foo = someNumber;
 
  return foo++;
}

To make it thread safe, it has to be modified as below:

static int foo;

static object sync = new object();
public static int AddOne(int someNumber)
{ 

  int myCalc;
 
  lock(sync)
  {
     foo = someNumber; 
    
     myCalc = foo++;
  }
 
  return myCalc;
}

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com