you can use the Monitor object to slightly improve performance, as indicated on MSDN:
Despite the fact that the mutex can be used to synchronize threads within a process, Monitor is usually used, since monitors were developed specifically for the .NET Framework and therefore use resources better
For more information
http://msdn.microsoft.com/en-us/library/system.threading.monitor.aspx
CancellationToken offers you a model for canceling asynchronous or long synchronous operations together. if you want to use it with a monitor class, you need to structure the code to release the lock if it is a cancellation request. You can do something below:
public void ThreadSafeMethod() { var cancellationToken=new CancellationToken(); object locker=new object(); Monitor.Enter(locker); try {
or if you want to use ThrowIfCancellationRequested:
public void ThreadSafeMethod() { var cancellationToken=new CancellationToken(); object locker=new object(); Monitor.Enter(locker); try {
Massimiliano peloso
source share