"c#: how can i make an ienumerable<t> thread safe?" Code Answer


there's an inherent problem in doing so, because ienumerator<t> has both movenext() and current. you really want a single call such as:

bool trymovenext(out t value)

at that point you can atomically move to the next element and get a value. implementing that and still being able to use yield could be tricky... i'll have a think about it though. i think you'd need to wrap the "non-threadsafe" iterator in a thread-safe one which atomically performed movenext() and current to implement the interface shown above. i don't know how you'd then wrap this interface back into ienumerator<t> so that you could use it in foreach though...

if you're using .net 4.0, parallel extensions may be able to help you - you'd need to explain more about what you're trying to do though.

this is an interesting topic - i may have to blog about it...

edit: i've now blogged about it with two approaches.

By Gyro Gearless on July 12 2022

Answers related to “c#: how can i make an ienumerable<t> thread safe?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.