I have code that looks like the following:
Mutex MyMutex = new Mutex();
Then later in parts that I want to make sure work at separate times:
void Part1()
{
MyMutex.WaitOne();
{//Do Stuff}
MyMutex.ReleaseMutex();
}
void Part2()
{
myTimer.Stop();
MyMutex.WaitOne();
{//Do other stuff that must be not at the saame time as Part1}
MyMutex.ReleaseMutex();
myTimer.Start();
}
Should this work? Part1 is triggered via a FileSystemWatcher and Part2
is triggered via a timer tick.
Hi Brian,
Possibly. But what happens if an error occurs somewhere, and your mutex
isn't released?
The best way, IMHO, to do this would be to use locking:
///
Object lockObject = new Object();
void Part1()
{
lock ( lockObject )
{
// Do Stuff
}
}
void Part2()
{
lock ( lockObject )
{
// Do Other Stuff
}
}
///
--
Hope this helps,
Tom Spink
Google first, ask later.
I'll give it a try. I'm still not sure why my Mutex code wasn't
working as hoped, I had try/catch/finally inside those mutex locks.
Meh. I'll see about the lock.
Brian Hampson
System Administrator
ALS Laboratory Group, North America
Code "like" what's pasted is rarely useful - it's easy to miss the bugs
out at the same time as stripping other things (like try/finally).
Could you post a short but complete program which demonstrates the
problem?
See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.
(I agree with Brian though - using lock is a lot better.)
--
Jon Skeet - <sk...@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
A Homer moment :(
In THEORY, however (if I hadn't had that leaking MUTEX issue)... was my
concept of Mutex implementation sound?
Brian Hampson
Well, the theory of "wait for the mutex, then release it" is sound - so
long as you don't have multiple mutexes and obtain them in different
orders, etc.