Доброго дня
Как я понял надо использовать ReaderWriterLockSlim отсюда
https://docs.microsoft.com/en-us/dotnet/api/system...
Сделал вроде все как у них, вылетает c System.NullReferenceException: 'Object reference not set to an instance of an object.'
using System;
using System.Threading;
public class Player {
public int id;
public override string ToString() {
return id.ToString();
}
}
public class SlimTest{
ReaderWriterLockSlim locker = new ReaderWriterLockSlim();
Random R = new Random();
Player _leader;
public Player leader {
get {
locker.EnterReadLock();
try {
return _leader;
}
finally {
locker.ExitReadLock();
}
}
}
int _id = 0;
public SlimTest() {
var main = new Thread(() => {
while(true) {
locker.EnterWriteLock();
try {
var cf = R.Next(1, 10) % 2;
if(cf > 0)
_leader = new Player() { id = _id += 1 };
else
_leader = null;
}
finally {
locker.ExitWriteLock();
}
Thread.Sleep(R.Next(3, 10));
}
});
main.IsBackground = true;
main.Start();
for(int i = 0; i < 10;i++) {
var reader = new Thread(() => {
while(true) {
if(leader != null) {
Console.Write(leader.id); // <<==System.NullReferenceException: 'Object reference not set to an instance of an object.'
}
else
Console.Write(".");
Thread.Sleep(R.Next(3, 10));
}
});
reader.IsBackground = true;
reader.Start();
}
}
}