What is the proper method for cleaning up EventWaitHandle?

Hi all,
I'm working on inter-process communication between applications running on the same machine. More specifically I have a primary application that is connected to multiple industrial machines collecting data from each.
I want to create secondary applications that consume this data. I intend on using MemoryMappedFile to share the information. I've tested the MMF part and it works fine.
I'm at the point where I want to notify the client applications when new data is available by using an EventWaitHandle. I create the handle as follows.
handle = new EventWaitHandle(false, EventResetMode.AutoReset, ClientName);
In the client application I use WaitOne inside a thread for the event notification. This too works well.
private void MonitorForSignal()
running = true;
bool signaled;
while (running)
signaled = handle.WaitOne();
if (signaled)
if (!handle.SafeWaitHandle.IsClosed)
//Do something
I create the thread as follows:
monitor = new Thread(MonitorForSignal);
monitor.IsBackground = true;
running = true;
monitor.Start();
My concern is that I may be creating an orphaned thread or a memory leak when I close the client application. So I implemented IDisposable in my client class and do the following.
protected virtual void Dispose(bool disposing)
if (disposing)
// free managed resources
// free native resources here if there are any
running = false;
handle.Close();
handle.Dispose();
monitor.Abort();
I believe this does indeed free the resources, but I've read that Thread.Abort is "bad". Before I implemented IDisposable I did some testing in a couple of WinForm applications, one acting as the host and one as the client. I noticed that I could
close the client and subsequently Set the EventWaitHandle in the host application and this line of code in the client would fire in the debugger.
signaled = handle.WaitOne();
This made me worry that I wasn't properly cleaning up my thread objects.
Below is the entire client for reference. What I'm really asking is how do I properly clean up the MonitorForSignal thread and the EventWaitHandle in the client?
public class ClientA : IDisposable
bool running;
string clientName;
EventWaitHandle handle;
Thread monitor;
private void MonitorForSignal()
running = true;
bool signaled;
while (running)
signaled = handle.WaitOne();
if (signaled)
if (!handle.SafeWaitHandle.IsClosed)
//Do something
private void ProcessData()
//Do Something
public ClientA(string ClientName)
if (ClientName == null || ClientName == string.Empty)
throw new ArgumentException("Cannot be null or empty.", "ClientName");
clientName = ClientName;
handle = new EventWaitHandle(false, EventResetMode.AutoReset, ClientName);
monitor = new Thread(MonitorForSignal);
monitor.IsBackground = true;
running = true;
monitor.Start();
#region IDispose
~ClientA()
Dispose(false);
public void Dispose()
Dispose(true);
GC.SuppressFinalize(this);
protected virtual void Dispose(bool disposing)
if (disposing)
// free managed resources
// free native resources here if there are any
running = false;
handle.Close();
handle.Dispose();
monitor.Abort();
#endregion
Regards,

Hi Michael,
Does this code cause the thread to spin?
while (!handle.WaitOne())
//TODO: Do work
Thread.Sleep(1000);
I was hoping not to spin thus the EventWaitHandle. As for the named handle, I am building multiple applications that need to have inter-process communication, all running on the same machine.
I think I can update my class to use your recommendation for the dispose method, specifically using handle.Set
However, I would update the MonitorForSignal as follows:
bool _closing = false;
private void MonitorForSignal()
running = true;
bool signaled;
while (running)
signaled = handle.WaitOne();
if (signaled && !_closing )
if (!handle.SafeWaitHandle.IsClosed)
if (NewData != null)
NewData();
And the dispose as follows:
protected virtual void Dispose(bool disposing)
if (disposing && handle!=null)
running = false;
_closing = true;
handle.Set();
if (!monitor.Join(5000))
monitor.Abort();
monitor = null;
handle.Dispose();
handle = null;
// free managed resources
// free native resources here if there are any
This allows me to skip over the "Do Work" part which should only be done when Signaled from another application. Your suggestion to use handle.Set() in the dispose method coupled with adding the bool _closing allows me to get past the EventWaitHandle
and also skip the work when closing.
Also by setting "running" to false in the dispose, the thread will naturally end after the wait handle has been set.
Thanks for suggesting the Thread.Join, that does seem allot more graceful. When I tested these changes it was blazing fast. In the previous code when I called monitor.Abort the application would hang for about a second. 
Do you think the changes capture the intent of your suggestions?
Regards,

Similar Messages

  • What is the proper method for embedding image files in a documentDB model?

    I'm working on some standard CMS functionality to produce simple service articles for a website. I'm looking at two possible options but I'm not sure which way to go.
    Example 1:
    I really want to create a value object to represent the image such as 
    class ImageFile
    public byte[] fileData { get; set;}
    public string contentType { get; set;}
    class WebArticle
    public ImageFile {get; set}
    public string someContent { get; set; }
    Or am I stuck with storing the image seperately w/ Azure Storage and just simply using my documentDB object to reference it's url via something like this:
    class WebArticle
    public string imageUrl { get; set; }
    public string someContent { get; set; }
    I see that there is some way to add "Attachments" but I'm not really clear on what the attachments are for. I don't think that I am reading the correct documentation. Is there a webpage out there that clarifies this. A kindle book on Amazon maybe?
    I'm looking forward to using this new technology. Ryan's Channel 9 presentation on the subject really caught my attention.
    Thank,
    Dan Jerome

    Ryan C:
    https://code.msdn.microsoft.com/Azure-DocumentDB-NET-Code-6b3da8af
    Mimi G:
    http://azure.microsoft.com/en-us/documentation/articles/documentdb-resources/

  • What is the proper method for creating a document with double spacing?

    There was a questioned posed regarding double spacing documents and it was suggested to set the leading to twice that of the font size.  Is this how "double spacing" is defined?

    Double-spacing is a concept traditionally used in word processing. In professional page layout, as you would use it in InDesign, the space between lines is called "leading" and refers to finer increments than word processing (Word's Single, 1.5 lines, Double, etc.) It is measured in units called "points." There are 12 points in an inch.
    In most professionally laid out publications, body copy of average column width is set with 1 to 4 points of space beyond the point size of the type. If the type size were 11 point, the leading might be set as between 12 and 15 points, depending on how much space you desired between lines.
    Why don't you tell us what is you're trying to accomplish, and perhaps attach a screen capture of what you're trying to do?

  • What's the proper protocol for a reset on my ipod touch 4g?  iOS 6 has totally jacked it up and it will no longer do anything but crash, and won't sync with itunes wirelessly or by cable.

    What's the proper protocol for a reset on my ipod touch 4g?  iOS 6 has totally jacked it up and it will no longer do anything but crash, and won't sync with itunes wirelessly or by cable.
    It's a 64G ipod touch and was fine till Apple told me to upgrade to ios 6.  Now most of my apps crash, my music won't play and I just get a white screen when I hit Music.
    When I try to sync to itunes it acts like it's going to sync and appears to recognize the ipod, but it's grayed out and has an update circle by it that spins for a while until itunes eventually freezes alltogether.  Is there a  way to go back to ios 5 after a erase and reset?

    iOS: Unable to update or restore

  • What is the best method for saving files off of the hard drive?

    I would like to save music files and photos somewhere other than my hard drive (eg. CDs, DVDs, zip disks). What is the best method for doing this?

    It rather depends on how paranoid you are
    External hard drives protect you from hard disk trouble on your machine.
    Optical media (CD's, DVD's) protect you from trouble with magnetic disks - such as external hard drives and the HD in your machine. Optical disks are thought to be more reliable that magnetic disks for long term storage.
    Off site back-ups will protect you from fire or theft at your home or office.
    How paranoid are you? Personally everything is backed up across three diferent external HD's. And maybe twice a year I burn a copy of my photos onto DVDs and they go to a relative's house across town.
    Regards
    TD

  • What is the best method for transferring iTunes library from PC to iMac?

    I have a new iMac.  I have authorized it with my iTunes account.  My current iTunes library is on a Windows Vista PC, not on the same network.  What is the best method for me to use to transfer the iTunes library from the PC to the iMac?
    iMac, Mac OS X (10.7.4)

    Did I just answer this in another post for you?
    iTunes: How to move [or copy] your music to a new computer [or another drive] - http://support.apple.com/kb/HT4527
    Quick answer if you let iTunes manage your music:  Copy the entire iTunes folder (and in doing so all its subfolders and files) intact to the other drive.  Start iTunes with the option (shift on Windows) key held down and guide it to the new location of the library.
    Macworld - How to transfer iTunes libraries between PC and Mac - http://www.macworld.com/article/46248/2005/08/shiftitunes.html
    Move an iTunes library from a Windows PC to a Mac - http://www.macworld.com/article/1146958/move_itunes_windows_mac.html
    iTunes for Windows: Moving your iTunes Media folder - http://support.apple.com/kb/HT1364

  • What is the best method for finding duplicates in iPhoto?

    What is the best method for finding duplicates in iPhoto?  I would like them identified and then prompted to delete or not.

    iPhoto Library Manager - http://www.fatcatsoftware.com/iplm/ - , duplicate annahalitor, Decloner
    LN

  • What is the proper config for the Airport Extreme when a Voice over IP device is between the cable modem and the router.

    What is the proper config for the Airport Extreme when a Voice over IP device is between the cable modem and the router.  Its a VoIPo device. The cable modem is connected to the VoIP WAN port and the LAN port on the device feeds the Airport Extreme.  The VOIP is working fine, and my Mac are getting 10. addresses from the Airport Extreme.  But I do get confict messages and lose my connection periodicaly.  Looking for help.

    Its a VoIPo device.
    Per chance, is this device the Grandstream HT502?

  • What is the encryption method for the user's password?

    hi all,
    who knows what is the encryption method for the user's password?
    the password is 803004, and i get the encrypted string "D7EDED84BC624A917F5B462A4DCA05CDCE256EEEEEDC97D59A57930E06CF9781E022CC8E430FF04E"
    thanks,
    dan

    There is no default password for a guest user unless you've created one:
    (screenshot from the System Pref Guest User Pane)

  • What is the best app for cleaning up the hard drive?

    What is the best app for cleaning up the hard drive?

    No such application needed.
    Leave 10 to 15% disk space free.
    Restart once in a while.
    Keep a backup, clone preferably.
    If there is any problem with the disk, repair disk.
        Repair Disk
        Steps 1 through 7
        http://support.apple.com/kb/PH5836
    Best.

  • What's the best method for a nav menu with image rollover for all visitors?

    Hi.
    First, thanks for reading this.
    What's the best method for a nav menu with image rollovers for all visitors, including PDAs? I've used JavaScript rollovers for years because the majority of my customers' visitors use some version of IE (past 7.0) but I'm building a new site that has to display properly for the widest range of visitors imaginable. (I also know that I need to use a more modern method for everyone and this is my excuse to start).
    Finally, using images is critical. I apologize ahead of time to anyone I offend, but I have never seen a nav menu without images that doesn't look just plain terrible.
    Thanks.
    Fitz21

    If you want the best menus possible for Dreamweaver look no further than Project Seven:
    http://projectseven.com/
    They have all kinds of menus and other extensions available for purchase.  Easy to use and they work as advertised.  I personally use Pop Menu Magic and Tab Panel magic myself.  I could go on and on, but I guarantee that if others respond they will echo the same sentiment for Project Seven.

  • HT1229 what is the best method for using a iphoto with an external hard drive for greater capacity?

    what is the best method for using a iphoto with an external hard drive for greater capacity?

    Moving the iPhoto library is safe and simple - quit iPhoto and drag the iPhoto library intact as a single entity to the external drive - depress the option key and launch iPhoto using the "select library" option to point to the new location on the external drive - fully test it and then trash the old library on the internal drive (test one more time prior to emptying the trash)
    And be sure that the External drive is formatted Mac OS extended (journaled) (iPhoto does not work with drives with other formats) and that it is always available prior to launching iPhoto
    And backup soon and often - having your iPhoto library on an external drive is not a backup and if you are using Time Machine you need to check and be sure that TM is backing up your external drive
    LN

  • What is the best method for moving iTune Libraries from Old to New Computer

    Hello,
    Thanks in advance for any assistance you may offer.
    My Sony Vaio Desktop recently died and untimely death, so I just purchased an HP Notebook. I was trying to wait out the release of the possible update of the Macbook line. However the old computer didn't agree. This HP will tie me over till a new release.
    I've been doing weekly backups for over 3 years with a backup drive from Western Digital. At this point I just want to transfer my music in iTunes and applications from the App store that are loaded on to my iPod Touch into the new computer and then reauthorize and sync.
    My question is what's the best method. Oh another problem I'm having includes the latest iPhone & iPod Touch software problem of 3rd party apps not working along with the vanishing of my music on the Touch.
    Any guidance would be much appreciated.

    Open up a fresh copy of iTunes. Point iTunes in the direction of your Western Digital Harddrive. Import Folders.
    1. New Copy
    2. Edit -> Preferences -> Advanced -> General -> Change -> <the address of the iTunes library on WD>
    3. File -> Add Folder to Library -> <Select iTunes folder on WD>
    Always keep a backup of your iTunes Library file and the iTunes XML Document. If you have those, then it might be just as simple as copying those to your iTunes file folder. If you are not sure where they are, then do a search for iTunes.xml.

  • I use photo stills in my iMovie. I want them to last longer than a minute, but when I input 01: 45: 00, to signify one min. and 45 seconds, it doesn't accept it. What is the proper format for inputting minutes?

    I use photo stills in my iMovie. I want them to last longer than a minute, but when I input 1:45:00, to signify one minute and 45 seconds, it doesn't accept it. What's the proper way to input it?

    There are 30 frames in one second of video. So you can specify down to the frame level, which is 1/30th of a second.
    Is the Duration box switching to some other time every time you type in 1:45:00?
    For instance this is a 5 second clip plus 3 frames. To get this set properly I would type in 1:45:00, then click done. I don't know if it is different under older versions of iMovie, as I'm using iMovie '11 for thisi example.

  • What is the proper name for Mac OS? OS X? Apple Mac OS X?

    It's a tad bit confusing for me since I am new to Apple.
    What do you call it the true name for it?
    Apple Mac OS?
    OS X?
    If I type in OS X It shows all the versions released form Apple.
    Like in the snap shot below.
    http://i1157.photobucket.com/albums/p600/napninjanx/Snapshots/Untitled_zps2d1aa9 90.png
    When I searched for MAC OS it did not show the versions of released OS X for Apple.
    Like in the snapshow below.
    http://i1157.photobucket.com/albums/p600/napninjanx/Snapshots/2_zpsbae85e49.png
    But when I searched on eBay for Snow Leopard it showed the brand name
    http://i1157.photobucket.com/albums/p600/napninjanx/Snapshots/3_zpsbcb588ac.png
    Then I thought going by brand name and model is the way to know the proper name for it.
    I think the proper name for it is Apple Mac OS X that's how you type it in order to know other realses if I am not mistaken.

    You can call it Mac OS X or OS X and others will know what you mean.
    If you click the apple at the left side of the menu bar, About This Mac, you will see OS X so that is what Apple calls it.

Maybe you are looking for