2019-12-22 00:17:56 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Threading.Tasks;
|
2020-03-26 04:25:48 +00:00
|
|
|
|
using Xunit;
|
2019-12-22 00:17:56 +00:00
|
|
|
|
|
2020-03-26 04:25:48 +00:00
|
|
|
|
namespace Wabbajack.Common.Test
|
2019-12-22 00:17:56 +00:00
|
|
|
|
{
|
|
|
|
|
public class AsyncLockTests
|
|
|
|
|
{
|
2020-03-26 04:25:48 +00:00
|
|
|
|
[Fact]
|
2019-12-22 00:17:56 +00:00
|
|
|
|
public async Task Typical()
|
|
|
|
|
{
|
|
|
|
|
var asyncLock = new AsyncLock();
|
|
|
|
|
bool firstRun = false;
|
|
|
|
|
var first = Task.Run(async () =>
|
|
|
|
|
{
|
2020-04-17 03:52:19 +00:00
|
|
|
|
using (await asyncLock.WaitAsync())
|
2019-12-22 00:17:56 +00:00
|
|
|
|
{
|
|
|
|
|
await Task.Delay(500);
|
|
|
|
|
firstRun = true;
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
var second = Task.Run(async () =>
|
|
|
|
|
{
|
|
|
|
|
await Task.Delay(200);
|
2020-04-17 03:52:19 +00:00
|
|
|
|
using (await asyncLock.WaitAsync())
|
2019-12-22 00:17:56 +00:00
|
|
|
|
{
|
2020-03-26 04:25:48 +00:00
|
|
|
|
Assert.True(firstRun);
|
2019-12-22 00:17:56 +00:00
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
await Task.WhenAll(first, second);
|
|
|
|
|
}
|
|
|
|
|
|
2020-03-26 04:25:48 +00:00
|
|
|
|
[Fact]
|
2019-12-22 00:17:56 +00:00
|
|
|
|
public async Task Exception()
|
|
|
|
|
{
|
|
|
|
|
var asyncLock = new AsyncLock();
|
|
|
|
|
bool firstRun = false;
|
|
|
|
|
bool secondRun = false;
|
|
|
|
|
// Throw exception inside a lock
|
2020-03-26 04:25:48 +00:00
|
|
|
|
await Assert.ThrowsAsync<Exception>(() =>
|
2019-12-22 00:17:56 +00:00
|
|
|
|
{
|
|
|
|
|
return Task.Run(async () =>
|
|
|
|
|
{
|
2020-04-17 03:52:19 +00:00
|
|
|
|
using (await asyncLock.WaitAsync())
|
2019-12-22 00:17:56 +00:00
|
|
|
|
{
|
|
|
|
|
await Task.Delay(500);
|
|
|
|
|
firstRun = true;
|
|
|
|
|
throw new Exception();
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
await Task.WhenAll(
|
|
|
|
|
// Try to re-enter lock afterwards
|
|
|
|
|
Task.Run(async () =>
|
|
|
|
|
{
|
|
|
|
|
await Task.Delay(200);
|
2020-04-17 03:52:19 +00:00
|
|
|
|
using (await asyncLock.WaitAsync())
|
2019-12-22 00:17:56 +00:00
|
|
|
|
{
|
2020-03-26 04:25:48 +00:00
|
|
|
|
Assert.True(firstRun);
|
2019-12-22 00:17:56 +00:00
|
|
|
|
secondRun = true;
|
|
|
|
|
}
|
|
|
|
|
}),
|
|
|
|
|
// Add a timeout to fail if we cannot
|
|
|
|
|
Task.Run(async () =>
|
|
|
|
|
{
|
|
|
|
|
await Task.Delay(500);
|
|
|
|
|
if (!secondRun)
|
|
|
|
|
{
|
|
|
|
|
throw new ArgumentException();
|
|
|
|
|
}
|
|
|
|
|
}));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|