1

我有简单的问题,但仍然找不到合适的解决方案(C#)

  1. 假设我在主类中运行的主线程char[] arena_snapshot不时使用某些资源(解析它,基于此更新竞技场)。
  2. 此外,我启动了不断更新共享资源的工作线程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);;
            ...
        }
    }
}
4

1 回答 1

0

你试过吗?

    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;
            }
        }
    }
于 2013-09-30T21:51:37.490 回答