Dalamud/Dalamud/Utility/ThreadSafety.cs
Soreepeong 14a5e5b652 ConsoleWindow racecon fix and highlight
RollingList is not thread safe, but the lock around it was inconsistent,
resulting in occasional null value in the log list. Fixed by utilizing
ConcurrentQueue so that logs can be added from any thread without locks,
and reading from the queue and adding to the list from the framework
thread.

Also, added log line highlight feature.
2024-03-09 04:09:29 +09:00

61 lines
1.8 KiB
C#

using System;
using System.Runtime.CompilerServices;
namespace Dalamud.Utility;
/// <summary>
/// Helpers for working with thread safety.
/// </summary>
public static class ThreadSafety
{
[ThreadStatic]
private static bool threadStaticIsMainThread;
/// <summary>
/// Gets a value indicating whether the current thread is the main thread.
/// </summary>
public static bool IsMainThread => threadStaticIsMainThread;
/// <summary>
/// Throws an exception when the current thread is not the main thread.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when the current thread is not the main thread.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AssertMainThread()
{
if (!threadStaticIsMainThread)
{
throw new InvalidOperationException("Not on main thread!");
}
}
/// <summary>
/// Throws an exception when the current thread is the main thread.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when the current thread is the main thread.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AssertNotMainThread()
{
if (threadStaticIsMainThread)
{
throw new InvalidOperationException("On main thread!");
}
}
/// <summary><see cref="AssertMainThread"/>, but only on debug compilation mode.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void DebugAssertMainThread()
{
#if DEBUG
AssertMainThread();
#endif
}
/// <summary>
/// Marks a thread as the main thread.
/// </summary>
internal static void MarkMainThread()
{
threadStaticIsMainThread = true;
}
}