When two threads access the same resource (for example, not local copies, but actually the same copy of the same resource), several things can happen. In the most obvious scenario, if Thread # 1 accesses a resource and Thread # 2 modifies it in the middle of reading, unpredictable behavior may occur. Even with something as simple as an integer, you might get logical errors, so try to imagine the horrors that might arise from the misuse of something more complex, such as a database access class that is declared static.
The classic way to solve this problem is to block sensitive resources, so only one thread can use it at a time. So in the example above, Thread # 1 will request a resource lock and get it, then go in to read what you need to read. Topic number 2 will come in the middle of reading and request a resource lock, but will be refused and will be asked to wait, because Thread # 1 uses it. When Thread # 1 ends, it releases the lock, and it is OK for Thread # 2 to continue.
There are other situations, but this illustrates one of the most basic problems and solutions. In C # you can:
1) Use specific .NET objects that are managed as wireframe locked (e.g. Scorpion-Prince for SynchronizedCollection )
2) Use [MethodImpl (MethodImplOptions.Synchronized)] to indicate that a particular method that does something dangerous should be used only one thread at a time
3) Use a lock statement to isolate certain lines of code that do something potentially dangerous
Which approach best really depends on your situation.
source share