neosmart / AsyncLock

An async/await-friendly lock for .NET, complete with asynchronous waits, safe reëntrance, and more.
https://neosmart.net/blog/2017/asynclock-an-asyncawait-friendly-locking-library-for-c-and-net/
MIT License
193 stars 28 forks source link

Nuget Package NeoSmart.AsyncLock bug #5

Closed a878851497 closed 3 years ago

a878851497 commented 5 years ago
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TestCore
{
    class TestAsyncQueue
    {
        AsyncQueue<string> asyncQueue = new AsyncQueue<string>();

        public void Test()
        {
            asyncQueue.Handler = DoProcess;

            for (int i = 0; i < 10; i++)
            {
                asyncQueue.Enqueue(i.ToString());
            }

        }
        private async Task DoProcess(string data)
        {
            await Task.Delay(1000);
            Console.WriteLine(DateTime.Now + "   " + data);
        }

    }

    public class AsyncQueue<T>
    {
        //private readonly Nito.AsyncEx.AsyncLock _lock = new Nito.AsyncEx.AsyncLock();
        private readonly NeoSmart.AsyncLock.AsyncLock _lock = new NeoSmart.AsyncLock.AsyncLock();

        public Func<T, Task> Handler { get; set; } = (t) => Task.CompletedTask;

        public async void Enqueue(T item)
        {
            using (await _lock.LockAsync())
            {         
                Console.WriteLine("start task " + item);
                await Handler.Invoke(item);
                Console.WriteLine("end task" + item);
            }            
        }
    }
}

image

version : 0.3.0.2

mqudsi commented 3 years ago

AsyncLock 3.0 should be able to handle this better.