473,785 Members | 2,669 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help with Mutex

I'm new to getting multi-threading working in C#, so I'm looking for
some help with Mutexes.
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.Release Mutex();
}

void Part2()
{
myTimer.Stop();
MyMutex.WaitOne ();
{//Do other stuff that must be not at the saame time as Part1}
MyMutex.Release Mutex();
myTimer.Start() ;
}

Should this work? Part1 is triggered via a FileSystemWatch er and Part2
is triggered via a timer tick.

Nov 15 '06 #1
5 3166
Brian Hampson wrote:
I'm new to getting multi-threading working in C#, so I'm looking for
some help with Mutexes.
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.Release Mutex();
}

void Part2()
{
myTimer.Stop();
MyMutex.WaitOne ();
{//Do other stuff that must be not at the saame time as Part1}
MyMutex.Release Mutex();
myTimer.Start() ;
}

Should this work? Part1 is triggered via a FileSystemWatch er 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.
Nov 15 '06 #2
Thanks,

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
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.
Nov 15 '06 #3
Brian Hampson <br***********@ gmail.comwrote:
I'm new to getting multi-threading working in C#, so I'm looking for
some help with Mutexes.

I have code that looks like the following:
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.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 15 '06 #4
Well, I've gone to the lock for now, and when I was stripping all the
comments out of the original function, I found that I had a return that
wouldn't release the mutex in certain circumstances. Doh!

A Homer moment :(

In THEORY, however (if I hadn't had that leaking MUTEX issue)... was my
concept of Mutex implementation sound?

Brian Hampson

Jon wrote:
Brian Hampson <br***********@ gmail.comwrote:
I'm new to getting multi-threading working in C#, so I'm looking for
some help with Mutexes.

I have code that looks like the following:

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.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 15 '06 #5
Brian Hampson <br***********@ gmail.comwrote:
Well, I've gone to the lock for now, and when I was stripping all the
comments out of the original function, I found that I had a return that
wouldn't release the mutex in certain circumstances. Doh!

A Homer moment :(

In THEORY, however (if I hadn't had that leaking MUTEX issue)... was my
concept of Mutex implementation sound?
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.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 15 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2667
by: Didier FRAISSE | last post by:
i want to be sure that only one instance of my script is running at the same time i try this little script #--------------------------------------------------------------------------- # -*- coding: cp1252 -*- from win32event import CreateMutex from win32event import ReleaseMutex from win32api import GetLastError
0
4408
by: Srijit Kumar Bhadra | last post by:
Hello, Here is some sample code with pywin32 build 203 and ctypes 0.9.6. Best regards, /Srijit File: SharedMemCreate_Mutex_win32all.py # This application should be used with SharedMemAccess_Mutex_ctypes.py or SharedMemAccess_Mutex_win32all.py
5
3804
by: Ken Varn | last post by:
I have a named mutex object that is accessed by both an asp.net application and a Windows executable .net application. The Windows executable runs under the administrator logon, while the asp.net application runs under the standard asp.net user account. The problem relates to permissions on creation of the mutex. If the asp.net application creates the mutex, the executable cannot access it (access denied error). Likewise, if the...
1
2251
by: Rocky | last post by:
I am using the following piece of code to ensure that my application only runs once, however I have a few questions about it. static Mutex m_Mutex; << in c# I assume that when the methods are static, so are the private members public static void Run(Form mainForm) { if(IsFirstInstance()) {
193
9648
by: Michael B. | last post by:
I was just thinking about this, specifically wondering if there's any features that the C specification currently lacks, and which may be included in some future standardization. Of course, I speak only of features in the spirit of C; something like object-orientation, though a nice feature, does not belong in C. Something like being able to #define a #define would be very handy, though, e.g: #define DECLARE_FOO(bar) #define...
16
3163
by: Ed Sutton | last post by:
I use a mutex to disallow starting a second application instance. This did not work in a release build until I made it static member of my MainForm class. In a debug build, first instance got ownership, second did not and terminated. In a release build, the second instance *also* got ownership. I "fixed" it by making the mutex a static member of my MainForm class. Did the garbage collector eat my mutex because it is not referenced
11
1951
by: mwt | last post by:
Hi. I'm reworking a little app I wrote, in order to separate the data from the UI. As a start, I wanted to create a iron-clad data recepticle that will hold all the important values, and stand up to being queried by various sources, perhaps concurrently. In all likelihood, the app will never need anything that robust, but I want to learn to write it anyway, as an exercise. So here is my code. It's really simple, and I'm sure you can see my...
1
1618
by: anadiks | last post by:
Problem 2: Threading: Requirements: In a particular system there are two threads T1 and T2. T1 is the master thread that periodically sends messages to the worker thread T2. The system is time-critical and hence T2 must react to every message that T1 sends.
3
5595
by: NaeiKinDus | last post by:
Hello, i'm trying to program a thread that would be locked (by a mutex) and that would only be unlocked once that a function (generating data) is done. The purpose is to generate data, and unlock the mutex in order to activate the thread once the data is generated. I have to do it this way, i can only call the thread if the data are generated. ******************************************************** step 1: initialize the mutex
11
3694
by: Lamont Sanford | last post by:
Given an object of type Mutex, what method or property should be called to determine if it is currently owned? I could call WaitOne(0,false) -- and if the return value is false, I could deduce that the Mutex is already owned... but this has the unwanted side effect of seizing ownership of the Mutex in the case where the Mutex is NOT already owned. I'm looking for something like an "IsOwned" property.
0
10324
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10090
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8971
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5380
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4050
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.