It seems that I found the answer and the question is also in this process.
The real question was whether it is possible to trust local "variables", which are actually objects, for simultaneous access. The answer is no, if they have an internal state that is not processed in a thread-safe manner, all bets are disabled. Closing does not help, it just captures the link to the specified object.
In my specific case - reading from IEnumerable<T>
at the same time and not writing to it, it is actually thread safe, because every call to foreach
, Contains()
, Where()
, etc. gets a new new IEnumerator
, which is displayed only from the thread that requested it. However, any other objects must also be checked one by one.
So cheers, no locks or synchronized collections for me :)
Thanks to @ebb and @Dave, although you did not answer the question directly, you pointed me in the right direction.
If you are interested in the results, this is the launch on my home PC (quad) using Thread.SpinWait
to simulate the string processing time. The real application improved by almost 2X (01:03 vs. 00:34) on a dual-core hyper-threaded machine with SQL Server on the local network.
Single threaded using foreach
. I donβt know why, but there are a fairly large number of contextual context switches.
Using Parallel.ForEach
, do not require locking with thread locators where necessary.
Vladislav Zorov
source share