Benny
Benny

Reputation: 3917

.NET Multithreading Syncronization

Quick version of my question:

Is the only time you need to use "lock" when you are accessing the same instance of an object? For example, if i am instantiating everything new within my thread entry method, do I have to worry about locking any objects?

Detailed Explanation of my question:

My scenario is, I have a work object with a unique identifier, and that work object has 1 method in it. Inside that method, I create new instances of multiple web service proxies and store the information retrieved from those calls in public properties of the work object. Once all work has been done (all threads have finished), I store the information to a database.

Any reason to consider using "lock"?

Upvotes: 0

Views: 188

Answers (3)

David
David

Reputation: 11

You only need to use the lock keyword if you are accessing a static field or property from multiple threads.

Upvotes: 0

SLaks
SLaks

Reputation: 888087

You only need to use lock on one or more sections of code that should not be run simultaneously. For example, if you have code that uses the same List<T> on multiple threads, you would need to use a lock.

In your case, if you have a separate work object per thread, and if they don't interact with any other work objects or access any shared state, you should be fine.

For a more specific answer, please post more details, or, preferably, source.


EDIT: In response to your comment, it depends on the implementation of InvokeService. As long as it doesn't access any other static members, you'll probably run fine without any locks.

Upvotes: 1

ptg
ptg

Reputation: 791

You're quite right - you don't need to lock objects that are not accessed across threads.

However. Be careful that there are no global resources, (i.e. I/O streams), that are been accessed by multiple threads without synchronization.

Upvotes: 0

Related Questions