I have a client/server type application setup, similar to a bittorrent downloading program. However, torrents are sent to the client remotely.
The main piece of shared data is the list of files (torrents) to be downloaded.
I have to handle these cases concurrently:
- The server sends (via WCF) an updated list of files to download, meaning some new files are to be added to the list and some removed from the list (and some remain unchanged)
- At the same time files might complete download/change state so items in the list need to be updated locally with new states
- Local events on the client may cause some items in the list to expire, so they should be removed
I am using an MVVM architecture but I believe the viewmodel should map closely to the view so I have added a ‘services’ layer which is currently a bunch of Singletons (I know). One of which acts as a shared resource for said list, so I have a single collection being updated by multiple threads.
I want to move away from the Singletons in favor of dependency injection and immutable objects to reduce the deadlocks, “deleted/detached object” and data integrity errors I’ve been seeing.
However, I have little idea where to ‘keep’ the list and how to manage incoming events from different threads that may cancel/negate/override current processing of the list.
I am looking for pointers on handling such a scenario at a high level.
I am using Entity Framework for the items in the list as the data also needs to be persisted.
I have recently done something similar for a windows service checker. It ended up being very easy to implement too.
In your case I see the need for the following.
File – it sole purpose is to download a file and notify of changes.
FileManager – maintains a list of Files and adding new, removing ect.
The beauty of this is that you never need to update the UI from the background thread. What you are updating are readonly properties that only the background class will be writing too. Anything out side this class can only read so you don’t have to worry about locking. The UI binding system will get a notification that the property has changed when the PropertyChanged is raised and will then read the value.
Now for the manager
Now all you need to do in your view model is expose the ListOfFiles from the FileManager which is an observable collection. Notifications from it will let the binding system know when the UI needs to update.
Just bind the ListOfFiles to a ListView or similar, add a datatemplate for the File class which will let the list view know how to render each file.
Your WCF server and view model should have a reference to the same File Manager, WCF adds and removes files, viewmodel makes the ListOfFiles available to the UI.
This is just a rough hack to get the concept across. You will need to add your stuff as you see fit.
Let me know if this helped.