使类字段线程安全 [英] Making class fields thread-safe

查看:55
本文介绍了使类字段线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个由不同线程访问的值的 List.因此,我通过执行以下操作使其线程安全:

Say I have a List of values that I accessed by different threads. So I make it thread safe by doing something like this:

private static object syncObject;
syncObject = new Object();

public List<double> MyList
{
    get
    {
        lock(syncObject) { return myList;}
    }   
    set
    {
        lock(syncObject) { myList = value;}
    }
}

如果在我的一个函数中,我需要访问 ListCount 属性,它可能不再是线程安全的.那么我如何编写它以便即使在访问属性时也是线程安全的?

If in one of my functions, I need to access the Count attribute of the List, it may not be thread safe anymore. So how do I write it such that even when accessing the attributes, it will be thread safe?

推荐答案

就像 Willem van Rumpt 所说的,您只是同步了对该特定属性的访问,而不是使其线程安全.为了不重新发明轮子,您可以使用 System.Collections.Concurrent (https://msdn.microsoft.com/en-us/library/dd267312(v=vs.110)).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1)

Like Willem van Rumpt said, you just synchronized the access to that specific property, not made it thread safe. To not reinvent the wheel, you can use the collections from System.Collections.Concurrent (https://msdn.microsoft.com/en-us/library/dd267312(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1)

另一个更可行的选择是使用不可变列表.不幸的是,afaik .Net 在这里没有提供太多.我所知道的唯一实现是在 Microsoft.FSharp.Collections 中.这个命名空间中的列表是一个不可变的单链表.(虽然我没有在 C# 中使用过它).

Another more viable option would be to use an immutable list. Unfortunately, afaik .Net doesn't offer too much here. The only implementation I know about is in Microsoft.FSharp.Collections. The list in this namespace is an immutable singly-linked list. (although I haven't used it from C#).

更新:正如 Matías Fidemraizer 所指出的,有 System.Collections.Immutable nuget 包可用于 .net 4.5及以上包含多个不可变集合的实现.谢谢!

UPDATE: As Matías Fidemraizer noted, there is the System.Collections.Immutable nuget package available for .net 4.5 and above that contains implementations for multiple immutable collections. Thank you!

这篇关于使类字段线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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