Quantcast
Channel: VBForums
Viewing all articles
Browse latest Browse all 15758

Can I lock a collection in a multi thread application

$
0
0
I've inherited a multi threaded application. My multi threading knowledge is pretty woeful I'm afraid.

In a nutshell, the user can start and abort a fairly lengthy process. They can then restart that process, possibly abort it again and so on. The first thing that happens when they start is that a collection of items to process is populated based on selection the user has made. Let's call this thread the processing thread and the collection the toDoList.

There is a separate thread that is responsible for updating the UI with the status of the items in the toDoList. This is triggered by a timer tick and it iterates over toDoList using a For loop. Let's call this thread the display thread

The problem is that it's possible for a user to abort and restart the process while the display thread is part way through iterating over the toDoList. When this happens the processing thread clears and repopulates the toDoList which, in turn, causes the display thread to crash because it's iterating over a collection that's being amended (Collection was modified; enumeration operation may not execute.)

The obvious solution that jump to mind is that I want to somehow lock the collection before it's used in either thread. By way of a metaphor, the UI thread would want a shared (read) lock and the processing thread would want an exclusive (write) lock.

I've been googling and can find all sorts of ways of locking a section of code so that only one thread can enter it at a time but that's no good to me because the code paths are completely separate and unrelated, they just both access the same resource.

Any suggestions?

Viewing all articles
Browse latest Browse all 15758


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>