3

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

pantonis
  • 5,601
  • 12
  • 58
  • 115

2 Answers2

6

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

Trevor Pilley
  • 16,156
  • 5
  • 44
  • 60
1

Thread safe doesn't really mean anything without context. You need to be much more detailed about what you would consider acceptable and unacceptable. In your specific case, because you have a separate data context for each method, you don't need to worry about one of the inserts being "in the middle of" another insert, or in some other way causing one of them to fail entirely as a result of unsynchronized access to a shared resource (that would potentially be a problem if the data context was shared between threads).

However, the order of the inserts is entirely indeterminate. If the order of those operations matters then it's "not thread safe".

Additionally, if you were performing multiple operations that comprised a "transaction" it may or may not be "thread safe' depending on how you define thread safe. If each method were inserting 5 items you couldn't be sure that all five inserts were either before or after the other method's inserts (unless you explicitly added a lock to ensure that).

Servy
  • 202,030
  • 26
  • 332
  • 449