1
我有簡單的問題,但仍然無法找到合適的解決方案(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);;
...
}
}
}