如何使自定义线程安全通用列表在C#中返回整个列表? [英] How make custom Thread Safe Generic List return the whole list in C#?

查看:119
本文介绍了如何使自定义线程安全通用列表在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#中返回整个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆