简体   繁体   English

这个C#类/方法线程安全和并发访问安全吗?

[英]Is this c# class/method thread-safe and concurrent access safe?

In the code below, is attachments object thread-safe? 在下面的代码中,附件对象是线程安全的吗? If calling code make changes to the attachments object while application running multiple threads, what may happen? 如果在应用程序运行多个线程时调用代码对附件对象进行了更改,可能会发生什么?

Thanks. 谢谢。

public static class Util {
    public static int AddMessage(string message, IEnumerable<FileAttachment> attachments, Dictionary<int, object> customFieldValues = null, int? assigneeUserId = null) {
        foreach (FileAttachment current2 in attachments) {
            //do something
        }
    }
}

In the code below, is attachments object thread-safe? 在下面的代码中,附件对象是线程安全的吗? And if calling code make changes to the attachments object while application running multiple threads, what may happen? 而且,如果在运行多个线程的应用程序中调用代码对附件对象进行了更改,可能会发生什么?

There is nothing that suggests that attachments is thread safe here. 没有任何迹象表明attachments在这里是线程安全的。 If other threads have access to those instances, and change the properties within those objects, bad things could happen. 如果其他线程可以访问这些实例,并更改这些对象内的属性,则可能会发生不良情况。

A simple example - if the actual enumerable happens to be a List<T> , and another thread adds or removes an attachment, the foreach loop will throw as it enumerates due to the underlying collection changing... 一个简单的例子-如果实际的可枚举碰巧是List<T> ,并且另一个线程添加或删除了附件,则由于基础集合的更改, foreach循环将在枚举时抛出...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM