Answer the question
In order to leave comments, you need to log in
How to implement a Thread safe state object (written in one, read from many)?
Good afternoon
As I understand it, you need to use ReaderWriterLockSlim from here
https://docs.microsoft.com/en-us/dotnet/api/system...
I did everything like they have, crashes with 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();
}
}
}
Answer the question
In order to leave comments, you need to log in
var tmp_leader = leader;
Console.Write(tmp_leader == null ? "." : tmp_leader.id.ToString());
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question