Skip to content

NuExt.System's ReentrantAsyncLock also works #8

@matthew-a-thomas

Description

@matthew-a-thomas

https://github.com/IvanGit/NuExt.System/blob/71dee735da6603adfc8b08bd24c55d81d78f2d71/src/System/Threading/ReentrantAsyncLock.cs

using var asyncLock = new ReentrantAsyncLock();
for (var i = 0; i < 1000; i++)
{
    var raceCondition = 0;
    // You can acquire the lock asynchronously
    await asyncLock.AcquireAsync(async () =>
    {
        await Task.WhenAll(
            Task.Run(async () =>
            {
                // The lock is reentrant
                await asyncLock.AcquireAsync(async () =>
                {
                    // The lock provides mutual exclusion
                    raceCondition++;
                    await Task.CompletedTask;
                });
            }),
            Task.Run(async () =>
            {
                await asyncLock.AcquireAsync(async () =>
                {
                    raceCondition++;
                    await Task.CompletedTask;
                });
            })
        );
    });
    if (raceCondition != 2)
        throw new Exception();
}

Need to update documentation accordingly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions