Giter Site home page Giter Site logo

jovitakao / asynclock Goto Github PK

View Code? Open in Web Editor NEW

This project forked from neosmart/asynclock

0.0 1.0 0.0 26 KB

An async/await-friendly lock for .NET, complete with asynchronous waits, safe reëntrance, and more.

Home Page: https://neosmart.net/blog/2017/asynclock-an-asyncawait-friendly-locking-library-for-c-and-net/

License: MIT License

C# 100.00%

asynclock's Introduction

AsyncLock: An async/await-friendly lock

AsyncLock is an async/await-friendly lock implementation for .NET Standard, making writing code like the snippet below (mostly) possible:

lock (_lockObject)
{
  await DoSomething();
}

Unlike most other so-called "async locks" for C#, AsyncLock is actually designed to support the programming paradigm lock encourages, not just the technical elements. You can read more about the pitfalls with other so-called asynchronous locks and the difficulties of creating a reentrance-safe implementation here.

With AsyncLock, you don't have to worry about which thread is running what code in order to determine whether or not your locks will have any effect or if they'll be bypassed completely, you just write code the way you normally would and you'll find AsyncLock to correctly marshal access to protected code segments.

Using AsyncLock

There are only three functions to familiarize yourself with: the AsyncLock() constructor and the two locking variants Lock()/LockAsync() .

AsyncLock() creates a new asynchronous lock. A separate AsyncLock should be used for each "critical operation" you will be performing. (Or you can use a global lock just like some people still insist on using global mutexes and semaphores. We won't judge too harshly.)

Everywhere you would normally use lock (_lockObject) you will now use one of

  • using (_lock.Lock()) or
  • using (await _lock.LockAsync())

That's all there is to it!

Async-friendly locking by design

Much like theSemaphoreSlim class, AsyncLock offers two different "wait" options, a blocking Lock() call and the asynchronous LockAsync() call. The utmost scare should be taken to never call LockAsync() without an await before it, for obvious reasons.

Upon using LockAsync(), AsyncLock will attempt to obtain exclusive access to the lock. Should that not be possible in the current state, it will cede its execution slot and return to the caller, allowing the system to marshal resources efficiently as needed without blocking until the lock becomes available. Once the lock is available, the AsyncLock() call will resume, transferring execution to the protected section of the code.

AsyncLock usage example

private class AsyncLockTest
{
  AsyncLock _lock = new AsyncLock();
  
  void Test()
  {
    //the code below will be run immediately (and asynchronously, in a new thread)
    Task.Run(async () =>
       {
         //this first call to LockAsync() will obtain the lock without blocking
         using (await _lock.LockAsync())
         {
           //this second call to LockAsync() will be recognized as being a reentrant call and go through
           using (await _lock.LockAsync())
           {
             //we now hold the lock exclusively and no one else can use it for 1 minute
             await Task.Delay(TimeSpan.FromMinutes(1));
           }
         }
       }).Wait(TimeSpan.FromSeconds(30));

    //this call to obtain the lock is synchronously made from the main thread
    //It will, however, block until the asynchronous code which obtained the lock above finishes
    using (_lock.Lock())
    {
      //now we have obtained exclusive access
      //perform non-thread-safe operation safely here
    }
  }
}

asynclock's People

Contributors

mqudsi avatar dyarkovoy avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.