What is the best approach for making a function or set of statements thread safe in C #?

What is the best approach to make a function or set of operators thread safe in C #?

+2


source to share


7 replies


It depends on what you are trying to accomplish. If you want to make sure that only one thread will run a specific code at any given time, use lock

either Monitor

:

public void Func(...)
{
   lock(syncObject)
   {
      // only one thread can enter this code
   }
}

      



On the other hand, you want multiple threads to run the same code, but you don't want them to trigger race conditions by changing the same point in memory, don't write to static / shared objects that multiple can reach at the same time.

BTW. If you want to create a static object that will only be used in one thread, use the attribute ThreadStatic

( http://msdn.microsoft.com/en-us/library/system.threadstaticattribute(VS.71).aspx ).

+1


source


Do not use shared read / write state if possible. Go with immutable types.



+5


source


Take a look at the C # locking operator . Read Jon Skeet's article on multithreading in .net .

+5


source


Use the locking operator around shared state variables. Once you are thread safe, run the code through a code profiler to find bottlenecks and optimize those with more advanced multithreading constructs.

+1


source


The best approach will depend on your specific problem.

The simplest approach in C # is to "lock" resources shared by multiple threads using lock . This creates a block of code that can only be accessed by one thread: the one that received the "lock" object. For example, this property is thread safe using the blocking syntax:

public class MyClass
{
    private int _myValue;

    public int MyProperty
    {
        get
        {
            lock(this)
            {
                return _myValue;
            }
        }
        set
        {
            lock(this)
            {
                _myValue = value;
            }
        }
    }
}

      

The thread acquires the lock at the beginning of the block and releases the lock only at the end of the block. If no lock is available, the thread will wait until the lock is available. Obviously, accessing a private variable within a class is not thread safe, so all threads must access the value through the property to be safe.

This is the easiest way for threads to access shared data safely, but only touches the tip of the iceberg of slicing methods.

+1


source


Write the function in such a way that:

  • It does not change its parameters in any way.
  • It does not access any state outside of local variables.

Otherwise, race conditions are possible. The code must be carefully checked for such conditions and appropriate thread synchronization (blocking, etc.) must be implemented. Writing code that doesn't require synchronization is the best way to make it thread safe. Of course, this is often not possible - but it should be the first option considered in most situations.

+1


source


There is a lot to understand when you learn what "thread safety" means, and all the problems that arise (synchronization, etc.).

I would recommend reading this page to better understand what you are asking: Threading in C # . This gives a fairly complete overview of the subject, which sounds like it could be very helpful.

And Mehrdad is absolutely right - go with immutable types if you can help him.

0


source







All Articles