Friday, March 18, 2016

How to Release a Semaphore with a Using Block

I love that .NET has so many useful utilities available in the base framework. I often use the SemaphoreSlim, and I love that it supports async await. However, I don't like always having to create a try finally block around every use call to ensure that the release method gets called.

Below is a simple little extension method that will allow you to place the result of the Semaphore wait into a using block, thus ensuring that the dispose will always release the lock.

SemaphoreSlim Extensions

public static class SemaphoreSlimExtensions
{
    public static async Task<IDisposable> UseWaitAsync(
        this SemaphoreSlim semaphore, 
        CancellationToken cancelToken = default(CancellationToken))
    {
        await semaphore.WaitAsync(cancelToken).ConfigureAwait(false);
        return new ReleaseWrapper(semaphore);
    }
 
    private class ReleaseWrapper : IDisposable
    {
        private readonly SemaphoreSlim _semaphore;
 
        private bool _isDisposed;
 
        public ReleaseWrapper(SemaphoreSlim semaphore)
        {
            _semaphore = semaphore;
        }
 
        public void Dispose()
        {
            if (_isDisposed)
                return;
 
            _semaphore.Release();
            _isDisposed = true;
        }
    }
}

Unit Tests

public class SemaphoreSlimExtensionsTests
{
    [Fact]
    public async Task UseWaitAsync()
    {
        var semaphore = new SemaphoreSlim(1);
 
        Assert.Equal(1, semaphore.CurrentCount);
 
        using (await semaphore.UseWaitAsync())
        {
            Assert.Equal(0, semaphore.CurrentCount);
        }
 
        Assert.Equal(1, semaphore.CurrentCount);
    }
}

Enjoy,
Tom

45 comments:

  1. Sorry if you've answered this question elsewhere, but I couldn't find anything when I looked - is this code under any particular license?

    ReplyDelete
  2. https://rootcracks.org/manycam-pro-keygen-here/
    ManyCam Pro Crack could be a free webcam package and video oppressor that allows you to enhance your video chats and make wonderful live streams on multiple platforms at an equivalent time. With ManyCam, you’ll be able to create professional-looking broadcasts on your favourite platforms, record your screen, add several effects and for a lot of. Grow your business with like pro-looking, simple, live video. Build dynamic net conferences, improve video calls and create wonderful live streaming videos with Picture-in-Picture, multiple video sources and screen sharing.

    ReplyDelete
  3. https://latestcracked.com/cubase-pro-full-crack-download-here/
    Cubase Pro Crack it’s a great and outstanding workstation of audio. That supports various types of songs in audio and video with Midi controls. Through this, you can also produce and manage the catalogue. It allows you to merge two types of files of music. Also, it provides you control over cropping and managing other works. The appropriate program is legendary for audio workstations. Using this application, you can develop a combination of audio by mixing them.

    ReplyDelete
  4. https://fixedcrack.com/miracle-box-crack-full-key-free-download/
    Miracle Box Pro Crack is an android application that is used to resolve all kinds of problems. The software application is a much useful and handy program which used to make the mediate support for them. Also, the Miracle Box is much shinny and used to make an intuitive platform. While it also helps to make the fantastic kinds of tasks to make the flashing phones. While you can also use it to unlock the procedure from this program as well.

    ReplyDelete
  5. https://activatorpros.com/videopad-video-editor-8-cracked-here/
    NCH VideoPad Video Editor Crack the app supplies a lot of changeover results, assorted video marketing tools, in addition to tools for coping together with noise. The end result might be stored as WMV, asf, mpg, 3gp, mp4, movie, I pod, i-phone, PSP, cell phone, Pocket personal computer data files, and also additionally burned to DVD, compact disc, blue ray disks or immediately considered.

    ReplyDelete
  6. https://autocracking.com/anytoiso-crack-plus-serial-key/
    Anytoiso Crack is a useful place where you can easily find Activators, Patch, Full version software Free Download, License key, serial key, keygen, Activation Key and Torrents. Get all of these by easily just on a single click.

    ReplyDelete
  7. https://www.thecrackbox.com/lumion-10-pro-cracked/
    Lumion Pro Activation Code is very simple and not very difficult for users. They can easily use this software. Lumion Pro permits its users to create realistic scenes. This software gives you a lot of useful advantages for simple layouts and moments also. It can help you in water editing, model positioning, skies, landscape, and spectacle editors.

    ReplyDelete
  8. https://boxcracked.com/youtube-by-click-crack-with-serial-number/
    YouTube By Click Torrent high quality and well known downloading speed like IDM software (speed), you can download videos and movies. There is also thousand of tiny pro traits adds to its newly launched version. And also its developer arranged a comfortable and smooth user interface. So the software utilized can easily without any hesitation get the videos.

    ReplyDelete
  9. https://crackygame.com/sparkocam-serial-number-here/
    SparkoCam Crack is the best tool for video clip effects, which gives you the opportunity to submit an application. Therefore, this tool is for stay videos and chats. While you may take advantage of this instrument for virtually any type of webcam. While DSLR with this particular certainty these as Nikon, Canon, and several others. This tool is helpful for many flow tools for the USB web camera along with also computers.

    ReplyDelete
  10. https://crackedsoftpc.com/mixed-in-key-crack-full-serial-keys-here/
    Mixed In Key Cracked, the following report discusses how the way it is possible to ensure all of the weather included in your tunes article is harmonically harmonious is just a potent skill for virtually any audio manufacturer. Therefore, blended At crucial Studio Edition finds the secret of one’s loop or a sample in real life.

    ReplyDelete
  11. https://licensekeysfree.com/camtasia-studio-keygen/
    Camtasia Studio Crack is the most powerful program that is used to create video presentations and video tutorials. Further, this program serves as the all in one feature and it can help the users to edit the videos and record the videos. Moreover, this program gives you the ability to make amazing and eye-catching videos. However, now you don’t need to be an expert. Henceforth, you also no need to have special skills to use this program.

    ReplyDelete
  12. https://cracksmod.com/recuva-pro-crack-patch/
    “Saying thank you is more than good manners, it is good spirituality.

    ReplyDelete
  13. Kindness is a language which the deaf can hear and the blind can see.
    https://ziapc.org/iobit-uninstaller-pro-crack-2020/

    ReplyDelete
  14. Wow... the blog you give us is amazing, no wonder many people want to read this. This is definitely my favorite, I hope my website can become popular and make people happy to see it.

    Bloodborne CD Serial Key Generator

    ReplyDelete
  15. Good post! We will be linking to this great article on our
    site. Keep up the good writing.
    IsoBuster Registration key

    ReplyDelete
  16. Amazing! This blog looks just like my old one!
    It’s on a completely different subject but it has pretty much
    the same layout and design. Wonderful choice
    of colors!
    iobit malware fighter crack
    avast secureline vpn crack
    beyond compare crack

    ReplyDelete
  17. I am typically to blogging and i really respect your content.
    The article has actually peaks my interest.
    I am going to bookmark your site and preserve checking for brand new information.
    winzip crack

    ReplyDelete
  18. corel draw x7 serial number crack
    I am typically to blogging and i really respect your content.
    The article has actually peaks my interest.
    I am going to bookmark your site and preserve checking for brand new information.

    ReplyDelete
  19. Have you ever considered writing an ebook or guest authoring on other sites?
    I have a blog centered on the same information you discuss and would really like to have you share some stories/information. I know my viewers would value
    your work. If you are even remotely interested, feel free to
    send me an e-mail.
    I like your blog very much. Very beautiful colors and themes.
    Have you created this amazing website yourself? please replys
    Return because I am trying to build my website and want to know where you are from
    Or subject name. Thank you!

    sketchup pro crack

    ReplyDelete
  20. I’m extremely impressed along with your writing skills as smartly as with the structure to your weblog.
    Is that this a paid subject matter or did you modify it your self?
    Anyway stay up the excellent quality writing, it’s rare to peer a nice weblog like this one nowadays.
    acdsee photo studio standard crack
    wondershare uniconverter crack
    little snitch crack
    drivermax pro crack

    ReplyDelete
  21. EditPlus is basically a text editor software. This software as a java editor or a PHP editor for Windows. Further, this is a super software system program.

    ReplyDelete
  22. Recuva Pro is a powerful recovery software. It restores any deleted file from a user’s personal computer.

    ReplyDelete
  23. Wondershare Dr Fone is computer iOS and android software which, helps us to recover our deleted data. It performs very quickly.

    ReplyDelete

  24. What’s up, after reading this awesome article i am also
    delighted to share my knowledge here with mates.
    netbalancer crack

    ReplyDelete


  25. I really appreciate your smart writing as the design of your blog.
    Is it a payment issue, or have you treated yourself?
    In any case, the best thing about writing remains, it is rare to see such a beautiful web page like this one day.
    gridinsoft anti malware crack
    light image resizer crack
    sqlpro studio crack
    cyberghost vpn crack keygen full version

    ReplyDelete
  26. Retail Man POS lets you access every account information. We can change our account by using this. When we want to see our screen on other laptops and computers. We use Retail Man POS free download full version in any type of retailing business. This software is used in shopping malls and many other factories. Moreover, this is also useful in CA engineering. This is an excellent tool to manage and organize stock, sales, and purchase. We can show our mall’s money information on the computer. Home

    ReplyDelete
  27. Lumion Crack

    Lumion Pro is a ground-breaking, simple, and amusing to-utilize successful design representation apparatus that permits anybody to construct a 3D situation. Let, and afterward make delightful pictures, noteworthy video introductions, and live walkthroughs. Lumion will fix to separate that expectation to absorb information such that engages originators to render their own work and shutting the hole that can in some cases develop between the designer and the craftsman.

    ReplyDelete
  28. Hello, very nice website!! Man Excellent .. Wonderful ..
    I’ll bookmark your web site and take the feeds also? I am satisfied to find
    numerous helpful information here in the publish, we need to develop extra strategies in this
    regard, thanks for sharing.
    drivermax pro crack
    eset nod32 antivirus crack
    avast premier crack
    idm build serial key crack

    ReplyDelete
  29. youtube downloader
    Wow that's what I've been exploring for! This website exists here thanks to this website admin.

    ReplyDelete
  30. After studying many pages on your site, I love your blog.
    I have added it as a book to my catalog and will see it longer.
    Please check out my website and let me know what you think.
    movavi screen capture studio crack
    youlean loudness meter pro crack

    ReplyDelete



  31. This design is spectacular! You most certainly know how to keep a reader amused.
    Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Excellent job.
    I really enjoyed what you had to say, and more than that, how you presented it.
    Too cool!
    little snitch crack

    ReplyDelete
  32. This design is spectacular! You most certainly know how to keep a reader amused.
    Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Excellent job.
    I really enjoyed what you had to say, and more than that, how you presented it.
    Too cool!
    minitool power data recovery crack
    winzip crack

    ReplyDelete

Real Time Web Analytics