unos baghaii
unos baghaii

Reputation: 2679

how to make Thread safety and not thread safety

I have this code and I Wonder if it is thread safe or not!!

if it is thread safe, How to make it not safe and vice versa

namespace ThreadSafeTest
{
class Program
{
    static void Main(string[] args)
    {

        Task.Factory.StartNew(() =>
        {
            for (int i = 0; i < 1000; i++)
            {
                var user = new User() { Id = i };
                method(user);
            }
        });

        Task.Factory.StartNew(() =>
        {
            for (int i = 1000; i < 2000; i++)
            {
                var user = new User() { Id = i };
                method(user);
            }
        });


        Console.ReadLine();
    }
    static void method( User user)
    {
        Console.WriteLine($@"the {user.Id} is {user.Id}{user.Id}");
    }
}

public class User
{
    public int Id  { get; set; }
}
}

it is complicated to understand the concept Thanks

Upvotes: 1

Views: 370

Answers (1)

mjwills
mjwills

Reputation: 23820

Your code is thread-safe since there is no shared state (i.e. different threads aren't sharing the same object). The only 'shared-ness' is the call to Console.WriteLine which is thread-safe.

As an example of how to make it not thread-safe, change:

static void method( User user)
{
    Console.WriteLine($@"the {user.Id} is {user.Id}{user.Id}");
}

to:

private static List<User> list = new List<User>();
static void method( User user)
{
    list.Add(user);
    Console.WriteLine($@"the {user.Id} is {user.Id}{user.Id}");
}

since list.Add is not thread-safe.

Note that the above list.Add code may still sometimes work - but it is not guaranteed to work (and it will definitely fail if you run it for long enough).

Upvotes: 2

Related Questions