简体   繁体   中英

Is it safe for multiple threads to read from a Lookup<TKey, TElement>?

Is it safe for multiple threads to read from a Lookup<TKey, TElement> ?

Lookup<TKey, TElement> is immutable, however MSDN states:

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

Though I shudder to imagine it, I'm wondering if the machine that pumps out MSDN documentation could be incorrect.

因为我不喜欢冒险,我可能不得不在1年后调试一个模糊的多线程相关错误,我将假设在没有手动同步的情况下使用这个类是不安全的。

As long as there is no writing, doing just reading is thread-safe. This is valid in any case.

Your question is in a sense orthogonal to the notion of thread-safety. A write in combination with a write or read is not thread-safe, but multiple reads without writing are thread-safe.

What MSDN says about instance members not being guaranteed to be thread-safe can only be valid in case of non-thread-safe scenarios, which by definition imply a write operation.

This is standard disclaimer for all most classes as you've probably noticed. Some methods may be thread safe, but "are not guaranteed".

Generally it is safe to read from collection using multiple threads if there are no writers to collection. If you need to update collection at the same time - use appropriate synchronization or built in thread safe collections like SynchronizedKeyedCollection .

Because the Lookup<TKey,TElement> is immutable, means that you will get the same values for all members. It does not mean that the items stored in it cannot be modified. So the collection is indeed not thread safe. A perfect example would be that most linq is lazy evaluated, and creating the enumerator could involve executing the lazy code. Trying to enumerate in two separate threads could cause the collection to be realized twice producing the wrong result.

Update: Now that the source code is available on https://referencesource.microsoft.com it is confirmed that internal state is set during method calls without regard to multithreading meaning that you could have race conditions and the Lookup<TKey,TElement> class is in fact not thread safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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