What makes thread-safe?

  • struct & immutable are thread safe. so string is also thread safe as all you can do is read them.
  • Reading is safe, if all the threads are reading.
  • If a method only access variable scoped within the method then it is thread safe beacuse each thread has it’s own stack.
  • Also if method calls other method which only use local scoped variables.
public class Thing
{
    public int ThreadSafeMethod(string parameter1)
    {
        int number; // each thread will have its own variable for number.
        number = this.GetLength(parameter1);
        return number;
    }

    private int GetLength(string value)
    {
        int length = value.Length;
        return length;
    }
}

 

  • but if a method use any properties or fields then you need to use lock to ensure the values are not modified by a different thread.
public class Thing
{
    private string someValue; // all threads will read and write to this same field value

    public int NonThreadSafeMethod(string parameter1)
    {
        this.someValue = parameter1;

        int number;

        // Since access to someValue is not synchronised by the class,
        // a separate thread could have changed its value.
        number = this.someValue.Length;
        return number;
    }
}

To ensure proper concurrency you need to use lock.

Advertisements

Leave a comment

Filed under C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s