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

25 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

Real Time Web Analytics