web analytics
How to implement a thread-safe C# method? Options
renaudj
Posted: Thursday, September 28, 2017 8:54:09 AM

Rank:Member
Groups: Member
Joined: 12/21/2015
Posts: 19
Points: 117

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;
}
Sponsor
Posted: Thursday, September 28, 2017 8:54:09 AM
 
Users browsing this topic
Guest

Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.


© 2017 Digcode.com. All rights reserved.