Prakash Tripathi
Prakash Tripathi

Reputation: 479

When to use lock and unnamed mutex in .NET?

NET threading experts,

I know that lock works across threads within a process and 'named mutex' works across processes. However 'unnamed mutex' also seems to be working across threads (similar to lock). Now can someone throw the light on real world uses of unnamed lock which lock can't handle?

Thanks in advance!

Upvotes: 0

Views: 756

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127603

Mutexes can be passed as a parameter to a function, locks can't. Mutexes are also MarshalByRefObject so then can be passed between AppDomains.

There are sometimes situations where you would like to lock across AppDomains within a program, for that you can use a unnamed mutex.

lock is built on top of low level mutexes with some logic applied to them, and Mutex is just a direct managed wrapper of those low level mutexes. Don't think of it as a either/or situation, instead think of it more like the relationship of TcpClient vs WebClient, you can use TcpClient to do all of the things WebClient does but it is easier to use the higher layer abstraction to do your work.

Upvotes: 2

Related Questions