Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/SquidStd.Core/Interfaces/Threading/IEventLoopService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,7 @@ public interface IEventLoopService

/// <summary>Worst observed tick elapsed time in milliseconds.</summary>
double MaxTickMs { get; }

/// <summary>True when the calling thread is the dedicated event-loop thread.</summary>
bool IsOnLoopThread { get; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public sealed class EventLoopService : IEventLoopService, ISquidStdService, IMet
private double _maxTickMs;
private Thread? _thread;
private long _tickCount;
private volatile int _loopThreadId = -1;

/// <inheritdoc />
public long TickCount => Interlocked.Read(ref _tickCount);
Expand Down Expand Up @@ -56,6 +57,9 @@ public double MaxTickMs
}
}

/// <inheritdoc />
public bool IsOnLoopThread => _loopThreadId == Environment.CurrentManagedThreadId;

/// <inheritdoc />
public string ProviderName => "eventloop";

Expand Down Expand Up @@ -85,6 +89,9 @@ public ValueTask StopAsync(CancellationToken cancellationToken = default)
_cts.Cancel();
_thread?.Join(TimeSpan.FromSeconds(5));

// Reset so a recycled managed thread id can't later report as the loop thread.
_loopThreadId = -1;

return ValueTask.CompletedTask;
}

Expand Down Expand Up @@ -136,6 +143,8 @@ internal int Tick()

private void RunLoop()
{
_loopThreadId = Environment.CurrentManagedThreadId;

while (!_cts.IsCancellationRequested)
{
var work = Tick();
Expand Down
26 changes: 26 additions & 0 deletions tests/SquidStd.Tests/EventLoop/EventLoopServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,30 @@ public async Task StartStop_ExecutesPostedWork()

Assert.True(fired);
}

[Fact]
public async Task IsOnLoopThread_TrueInsidePostedWork_FalseOutside()
{
var dispatcher = new MainThreadDispatcherService();
var timer = new FakeTimerService();
using var loop = new EventLoopService(dispatcher, timer, new EventLoopConfig());

Assert.False(loop.IsOnLoopThread);

bool onLoopInside = false;
var signal = new ManualResetEventSlim(false);
dispatcher.Post(() =>
{
onLoopInside = loop.IsOnLoopThread;
signal.Set();
}
);

await loop.StartAsync();
signal.Wait(TimeSpan.FromSeconds(2));
await loop.StopAsync();

Assert.True(onLoopInside);
Assert.False(loop.IsOnLoopThread);
}
}
Loading