是否需要lock或Interlocked.Exchange来交换在另一个线程中使用的引用类型字段?

时间:2019-01-01 16:49:06

标签: c# multithreading thread-safety

我知道我可以使用一些.NET集合,它们是线程安全的,但是我仍然想了解以下情况:

我有一个Buffer类(如下),该类用于写入来自不同线程的数据,在更新循环间隔(游戏)中,主线程通过交换列表实例来处理数据(以防止两个线程作用于同一线程)实例)。

因此只有一个使用“ writerData”列表的附加线程,其他所有操作都在主线程上完成,但是我不确定Swap方法是否是“安全”线程,因为在搜索了一段时间后,每个人似乎对交换参考字段有不同的看法。

有人说交换引用不需要任何锁定,有人说在这种情况下必须使用Interlocked.Exchange,有人说不需要,而有人说必须违反字段,有人说关键字是“ evil”。 。

我知道线程是一个困难的话题,也许其他问题太广泛了,但是有人可以帮助我了解在Swap方法的特定情况下是否需要/哪种“锁定”?

public class Buffer
{
    List<byte> readerData; 
    List<byte> writerData; // This is the only field which is used by the other thread (by calling the Add method), well and by the Swap method, which is called from the main thread

    // This method is only called by the other thread and it's the only method which is called from there
    public void Add(byte data)
    {
        writerData.Add(data);
    }
    // Called on the main thread, before handling the readerData
    public void Swap()
    {
        var tmp = readerData;
        readerData = writerData
        writerData = tmp;
    }

// ... some other methods (which are only called from the main thread) to get the data from the (current) readerData field after calling the Swap method
}

0 个答案:

没有答案
相关问题