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

44 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. Thanks for sharing your experience .getmacos

    ReplyDelete

  26. Tor Browser
    Is this a paid topic or do you change it yourself?
    However, stopping by with great quality writing, it's hard to see any good blog today.

    ReplyDelete
  27. Computer science is the theoretical study of computer and software (Turing's essay is an example of computer science),

    sdata tool mrpirate

    Windows 10 Activator

    Internet Cyclone 2.28 Crack

    MikroTik 7.1 Beta 3 Crack 2021

    IObit Start Menu 8 Pro

    Whereas Software Engineering is the Application of Engineering and Development of Software,,,

    Bitdefender Total Security 2021

    Money Pro 2.7.10 Crack

    TechTool Pro Crack

    VCE Exam Simulator Crack

    Bandicut Crack

    Knowledge Has No End Limits Keep Sharing Your Knowledge //////////

    ReplyDelete
  28. I am very impressed with your post because this post is very beneficial for me and provide a new knowledge to me
    https://vstpincrack.com/

    ReplyDelete

  29. Win Zip Crack
    I'm really impressed with your writing skills, as smart as the structure of your weblog.

    ReplyDelete

  30. I like your all post. You have done really good work. Thank you for the information you provide, it helped me a lot. I hope to have many more entries or so from you.
    Very interesting blog.
    fullcrackedpc.com
    vsthomes.com

    ReplyDelete

Real Time Web Analytics