我有简单的问题,但仍然找不到合适的解决方案(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);;
...
}
}
}