struct Locker
{
private SpinLock _lock;
public Lock Acquire() => new(ref _lock);
}
ref struct Lock
{
private ref SpinLock _lock;
private bool _lockTaken;
public Lock(ref SpinLock @lock)
{
_lock = ref @lock;
_lock.Enter(ref _lockTaken);
}
public void Dispose()
{
if (!_lockTaken) return;
_lockTaken = false;
_lock.Exit();
}
}
I’m getting a CS8347 error on the line defining the Acquire
method. How do I get rid of it preserving the core functionality?
- I need the
Locker
structure to contain onlySpinLock
value - I need the
Lock
structure to contain a reference toLock
structure, or to their values +_lockTaken
field
6
Maybe this – move the ownership out one layer:
SpinLock obj = default;
using (obj.Acquire())
{
// ...
}
static class SpinLockExtensions
{
public static Lock Acquire(ref this SpinLock @lock)
=> new(ref @lock);
}