Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ To SQL Thread Safety

I want to ask whether the following code is thread safe: Consider that Save1 and Save2 will be executed concurrently. Is there any problem with the thread safety of the datacontext?

public class Test1()
{
    private void Save1()
    {        
        using(TestLinqToSQL obj = new TestLinqToSQL())
        {        
             obj.SaveRecord(new Client (){Id = 1, Name = "John Doe");
        }
    }

    private void Save2()
    {        
         using(TestLinqToSQL obj = new TestLinqToSQL())
         {        
             obj.SaveRecord(new Client (){Id = 2, Name = "Mike Tyson");
         }
    }         
}



public class TestLinqToSQL : IDisposable
{
    public void SaveRecord(Client newClient)
    {
        using(ClientDatacontext cont = new ClientDatacontext())
        {
            cont.InsertRecord(newClient);
        }        
    }
}

Thanks in advance

like image 996
pantonis Avatar asked Jun 20 '26 11:06

pantonis


1 Answers

In this case, no it is not a problem as each thread will get a separate DataContext instance since each method results in a new one being created. You would have a problem if the DataContext was shared between threads as the instance methods are not thread safe see MSDN

like image 157
Trevor Pilley Avatar answered Jun 22 '26 01:06

Trevor Pilley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!