32 lines
889 B
C#
32 lines
889 B
C#
namespace Bts.PubSub;
|
|
|
|
using BCG.Utilities.General;
|
|
|
|
using bts;
|
|
|
|
using System;
|
|
using System.Threading;
|
|
|
|
/// <summary>
|
|
/// An <see cref="IWorker"/> wrapper that asserts doWork is always called on the same thread.
|
|
/// </summary>
|
|
public class SingleThreadedWorker : IWorker {
|
|
readonly IWorker worker;
|
|
int threadId = noThreadId;
|
|
|
|
public SingleThreadedWorker(IWorker worker) =>
|
|
this.worker = worker;
|
|
|
|
static int noThreadId => -1;
|
|
|
|
public void doWork() {
|
|
var currThreadId = Environment.CurrentManagedThreadId;
|
|
if (!(currThreadId == threadId
|
|
|| Interlocked.CompareExchange(ref threadId, currThreadId, noThreadId) == noThreadId
|
|
|| currThreadId == threadId)) {
|
|
Log.assert(false, $"SingleThreadedWorker doWork called on a different thread. expectedThread: {threadId}, currentThread: {currThreadId}");
|
|
}
|
|
worker.doWork();
|
|
}
|
|
}
|