我有简单的问题,但仍然找不到合适的解决方案(C#)
char[] arena_snapshot
(解析它,根据此更新竞技场)。char[] arena_snapshot
。是否有可能在解析工作线程的过程中修改缓冲区,以便主线程错误地解析缓冲区。 如何在解析时锁定arena_snapshot?
class Arena
{
List<PLayer> players;
...
public int main()
{
arenaClient = new ArenaClient();
Thread arenaListener = new Thread(new ThreadStart(arenaClient.StartListener));
arenaListener.IsBackground = true;
arenaListener.Start(); //Start UDP worker
}
public void Update()
{
//Let's parse the buffer and update our Arena ..
...
foreach (Player p in players)
{
play.Position.X = arenaClient.arena_snapshot[2];
//etc...
}
}
}
class ArenaClient
{
...
public char[] arena_snapshot; //hold most recent information about our Arena (snapshot)
...
public void StartListener()
{
while(!done)
{
...
//Warning! Updating the snapshot, warn the main thread! Don't do this during parsing of the snapshot!
arena_snapshot = UDPClient.Receive(ref groupEP);;
...
}
}
}
答案 0 :(得分:0)
您是否尝试过lock?
private Object thisLock = new Object();
private char[] _arena_snapshot;
public char[] arena_snapshot
{
get
{
lock (thisLock)
{
return _arena_snapshot;
}
}
set
{
lock (thisLock)
{
_arena_snapshot = value;
}
}
}