如何使自定义线程安全通用列表在C

如何使自定义线程安全通用列表在C

本文介绍了如何使自定义线程安全通用列表在C#中返回整个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个线程菜鸟,我正在尝试在C#(.NET 3.5 SP1)中编写自定义线程安全的通用列表类.我已阅读为什么线程安全集合这么难?.复习完班级的要求后,我认为我只需要安全地 添加 到列表中并 返回 .该示例显示了我想要的几乎所有内容,但缺少 返回列表 方法,因此,我编写了自己的公共方法,如下所示:

I am a threading noob and I am trying to write a custom thread safe generic list class in C# (.NET 3.5 SP1). I've read Why are thread safe collections so hard?. After reviewing the requirements of the class I think I only need to safely add to the list and return the list. The example shows pretty much all I want except it lacks the return list method therefore I've written my own public method like below:

更新:根据给出的建议,我已经审查了我的要求,因此将该类简化为以下内容:

Update: based on suggestions given I've reviewed my requirements and therefore simplified the class to as below:

public sealed class ThreadSafeList<T>
{
    private readonly IList<T> list = new List<T>();
    private readonly object lockable = new object();

    public void Add(T t)
    {
        lock (lockable)
        {
            list.Add(t);
        }
    }

    public IList<T> GetSnapshot()
    {
        IList<T> result;
        lock (lockable)
        {
            result = new List<T>(list);
        }
        return result;
    }
}

推荐答案

同意@jrista.您需要解决一个语义问题,为什么将它称为Translate()?目的是什么?

Agree with @jrista. There's a semantics issue you need to resolve, and why is it called Translate()? What is the intent?

return new ReadOnlyCollection<T>(list);

如果在另一个线程遍历列表时更改了原始列表,则仍然存在线程问题.只要您知道这一点,这不是一个大问题.

You still have threading issues if the original list is changed if another thread is iterating over the list. As long as you're aware of this, it isn't a huge issue.

return new List<T>(list).AsReadOnly();

此列表没有线程问题,因为没有任何东西可以修改新列表.唯一保留的引用是ReadOnlyCollection<T>包装器.

This list has no threading issues because nothing modifies the new list. The only reference held is by the ReadOnlyCollection<T> wrapper.

return new List<T>(list);

返回一个新列表,并且呼叫者可以在不影响原始列表的情况下对自己的列表进行操作,并且对原始列表的更改也不会影响此列表.

Returns a new list, and the caller can do what they wish to their list without affecting the original list, and changes to the original list do not affect this list.

另一个消费者是否获取了列表的副本然后修改了副本,这有关系吗?消费者是否需要查看列表的更改?您是否只需要一个线程安全的枚举器?

Does it matter if another consumer grabs a copy of the list and then modifies their copy? Do consumers need to see changes to the list? Do you just need a thread-safe enumerator?

public IEnumerator<T> ThreadSafeEnumerator()
{
    List<T> copy;
    lock(lockable)
        copy = new List<T>(list);

    foreach (var value in copy)
        yield return value;
}

这篇关于如何使自定义线程安全通用列表在C#中返回整个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 10:36