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

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

I wouldn't say "potentially", it's virtually guaranteed to be a huge problem.
Thanks. What do you mean by instance methods?
The methods on the DataContext class which are only accessible once you have created one. In other words, methods which are not static.
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).

1 Comment

Thanks. That solved my scenario. I dont care about inserts order.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.