When designing an application, you should avoid thread synchronization whenever possible. To do this, avoid using some shared data, such as static fields.
When a thread constructs an object with the new operator, a reference to the new object is returned by the new operator. At this point, only the thread that constructs the object
has a reference to it; no other thread can access that object. If you can always avoid passing this reference to the one that might use the object at the same time
Another thread, you do not have to synchronize access to the object.
Try to use value types because they are always duplicated, so each thread is working on its own copy.
Finally, there is no problem with multiple threads having read-only access to shared data at the same time, for example, many applications will initialize them
Period to create some data structures. Once initialized, the application can create any number of threads it wants, if all the threads are only
is to query the data, all threads are queried at the same time without acquiring or releasing a lock. One example of this is the string type: once
Creates a good string object, which is "immutable." Therefore, many threads can access a string object at the same time, and the string object has no
Damage.
Making a method thread safe does not mean that it must internally acquire a thread synchronization lock.
A thread-safe approach means that data is not corrupted when two threads attempt to access data at the same time.
The System.Math class is a static Max method, which is implemented as follows:
public static Int32 Max (Int32 val1,int32 val2)
{
Retrun (VAL1<VAL2)? Val2:val1;
}
This method is thread-safe, even if it does not acquire any locks. Since Int32 is a value type, the two Int32 values passed to Max are copied to the method
Internal. Multiple threads can call the Max method at the same time, and each thread is processing its own data, and the threads do not interfere with each other.
When a thread constructs an object, only that thread has an object reference and no other thread can access that object, so the call to the
No thread synchronization is required for instance methods. However, if the thread then exposes the object reference----put it in a static field,
Pass it as a state argument to ThreadPool.QueueUserWorkItem or to a task----so many threads may simultaneously
For non-read-only access, thread synchronization is required.
Thread Sync notes