+ 1

How to modify, search and add to a collection in a thread-safe way

I have two threads using one collection. Thread 1 : add's elements to the collection Thread 2 : seraches and modfies the collection. Sometimes I get this error. Collection was modified; enumeration operation may not execute. Which means that Thread 1 tries to add something and Thread 2 want to search the collection for a specific element at the same time. How can I prevent this error from happening

19th Oct 2021, 9:53 AM
sneeze
sneeze - avatar
3 RĂ©ponses
+ 1
You can use Thread.Join(). It will block current calling thread until the thread calling Join() is completed, so the thread called Join() will definitely be completed in the moment. Example: https://code.sololearn.com/cdGHQSFU1Vof/?ref=app
19th Oct 2021, 11:30 AM
äœ çŸ„é“èŠć‰‡ïŒŒæˆ‘äčŸæ˜Ż
äœ çŸ„é“èŠć‰‡ïŒŒæˆ‘äčŸæ˜Ż - avatar
0
I recommend that you use Task.
21st Oct 2021, 7:11 AM
hossein B
hossein B - avatar
0
I do not start the threads myself. It is a timer that fires a Timer_Tick event and another event with various time interval. Most of the time these two event do not fire exact at the same time. When they do I get this error. CarrieForle How can I know the name of the thread ? hossein B How can I use Task ? This my code, it does not work in the playground. It does show what I want to achieve. https://code.sololearn.com/c96u4wpPzYjW/?ref=app
21st Oct 2021, 8:14 AM
sneeze
sneeze - avatar