Novice, beginner c #, would like to ask, if the two instances to control the same instrument, which one to use lock can achieve!
CodePudding user response:
The mutex, mutually exclusive, mutexesCodePudding user response:
With more "old" theory of lock, is a different code segment for Shared lock object, such aslock (localObj)and
{
. Code 1
}
lock (localObj)to ensure that the first will be the same as the lock semaphore object,
{
. Code 2
}
But it is more suitable for "lock" occasionally, traditional, is to assume that the lock (this) {... The lock {}, typeof (... )) {... } this type of code is easy to abuse, easy to cause the deadlock, but things are not necessarily absolute, even with The Times are different, could happen model inversion,
When you need a large number of processing high concurrency, high performance, the design of the large data, but to give up too "fine" lock concept, and to use the extended to the object itself, type "level of encapsulation, for example:
public class X machine
{
Public X machine (string id)
{
.
}
Public void to upload data ()
{
The lock (this)
{
.
}
}
Public void data set (valueType x)
{
The lock (this)
{
.
}
}
.
So to ensure the same object more open public interface operation "automatic locking", based on the mission of the asynchronous Task programming can be through SemaphoreSlim mechanism,
CodePudding user response:
What should pay attention to, not with "between two instances", or how many, how many kind of code to access the same object of so-called "sync lock", but, in the form of "object-oriented encapsulation" public interface method of exposing object itself guarantee is thread-safe,And when you found the lock is too "rough", can reduce the particle degree of the object encapsulation, increase the degree of concurrency,
Because all sorts of messy code "" require the programmer to forcibly programming to lock synchronization, easy to cause more interlock and missing, but completely put down the concept of" multiple instances of interlock ", instead, you can easily ensure that multiple instances of efficient programming and concurrent operation,