gpt4 book ai didi

.net - .Net 的 LinkedList 实现是线程安全的吗?

转载 作者:行者123 更新时间:2023-12-02 07:11:06 25 4
gpt4 key购买 nike

实际上,我正在开发一个应用程序,它使用多个线程来处理多个任务,父应用程序接收任务的输出,稍后写入文件,目前我正在使用 arraylist 将输出附加到,但是从队列中删除项目时这恰好很慢。 我正在考虑将 arraylist 部分转换为链表以优化读取和清除,任何人都可以确认我 如果 .Net 的 linkedList 实现是线程安全的,或者甚至使用 arraylist 也是线程安全的?

最佳答案

reference指出:

This type is not thread safe. If the LinkedList(Of T) needs to be accessed by multiple threads, you will need to implement their own synchronization mechanism.

A LinkedList(Of T) can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

编辑:

至于 ArrayList,reference状态:

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

An ArrayList can support multiple readers concurrently, as long as the collection is not modified. To guarantee the thread safety of the ArrayList, all operations must be done through the wrapper returned by the Synchronized method.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

关于.net - .Net 的 LinkedList 实现是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5789291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com