Skip to content

Commit

Permalink
Merge pull request #600 from caioavidal/build
Browse files Browse the repository at this point in the history
Fix thread blocking attribute
  • Loading branch information
caioavidal authored Dec 17, 2024
2 parents 7959ad4 + c5b9b44 commit ac1985f
Showing 1 changed file with 34 additions and 29 deletions.
63 changes: 34 additions & 29 deletions tests/NeoServer.Game.Tests/Helpers/ThreadBlockingAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,43 +3,48 @@
using System.Threading;
using Xunit.Sdk;

namespace NeoServer.Game.Tests.Helpers;

/// <summary>
/// Block the unit test to avoid concurrency
/// </summary>
public class ThreadBlockingAttribute : BeforeAfterTestAttribute
{
public override void Before(MethodInfo methodUnderTest) => ThreadBlocking.Wait();

public override void After(MethodInfo methodUnderTest) => ThreadBlocking.Release();
}

public static class ThreadBlocking
namespace NeoServer.Game.Tests.Helpers
{
private static readonly Mutex Mutex = new();
public static void Wait()
/// <summary>
/// Block the unit test to avoid concurrency.
/// </summary>
public class ThreadBlockingAttribute : BeforeAfterTestAttribute
{
try
{
Mutex.WaitOne();
// Mutex acquired
}
catch (AbandonedMutexException)
{
Console.WriteLine("Warning: Mutex was abandoned by another thread.");
}
public override void Before(MethodInfo methodUnderTest) => ThreadBlocking.Wait();

public override void After(MethodInfo methodUnderTest) => ThreadBlocking.Release();
}

public static void Release()
public static class ThreadBlocking
{
if (Mutex.WaitOne(0)) // Check if mutex is owned before releasing
private static readonly Mutex Mutex = new();
private static Thread _owningThread;

public static void Wait()
{
Mutex.ReleaseMutex();
try
{
Mutex.WaitOne();
_owningThread = Thread.CurrentThread;
// Mutex acquired
}
catch (AbandonedMutexException)
{
Console.WriteLine("Warning: Mutex was abandoned by another thread.");
}
}
else

public static void Release()
{
Console.WriteLine("Warning: Mutex was not owned by the current thread.");
if (_owningThread == Thread.CurrentThread)
{
_owningThread = null; // Reset ownership before releasing
Mutex.ReleaseMutex();
}
else
{
Console.WriteLine("Warning: Mutex was not owned by the current thread.");
}
}
}
}

0 comments on commit ac1985f

Please sign in to comment.