开发者

Concurrency architecture in an MVVM application

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.

public class File : INotifyPropertyChanged
    {
        private readonly string _fileName;
        private Thread _thread;
        private Task _task;
        private bool _cancelled;

        private TaskStatus _taskStatus;
        private int _taskProgress;
        private int _taskTotal;

        public event PropertyChangedEventHandler PropertyChanged;

        public File(string fileName)
        {
            _fileName = fileName;
            TaskStatus = TaskStatus.NotStarted;
        }

        public TaskStatus TaskStatus
        {
            get { return _taskStatus; }
            private set
            {
                _taskStatus = value;
                PropertyChanged.Raise(this, x => x.TaskStatus);
            }
        }

        public int TaskProgress
        {
            get { return _taskProgress; }
            private set
            {
                _taskProgress = value;
                PropertyChanged.Raise(this, x => x.TaskProgress);
            }
        }
        public int TaskTotal
        {
            get { return _taskTotal; }
            private set
            {
                _taskTotal = value;
                PropertyChanged.Raise(this, x => x.TaskTotal);
            }
        }

        public void StartTask()
        {
            _cancelled = false;

            //.Net 4 - task parallel library - nice
            _task = new Task(DownloadFile, TaskCreationOptions.LongRunning);
            _task.Start();

            //.Net Other
            _thread = new Thread(DownloadFile);
            _thread.Start();
        }

        public void CancelTask()
        {
            _cancelled = true;
        }

        private void DownloadFile()
        {
            try
            {
                TaskStatus = TaskStatus.Running;

                var fileLength = _fileName.Length;
                TaskTotal = fileLength;

                for (var i = 0; i < fileLength; i++)
                {
                    if (_cancelled)
                    {
                        TaskStatus = TaskStatus.Cancelled;
                        return;
                    }

                    //Some work to download the file
                    Thread.Sleep(1000); //sleep for the example instead 

                    TaskProgress = i;
                }

                TaskStatus = TaskStatus.Completed;

            }
            catch (Exception ex)
            {
                TaskStatus = TaskStatus.Error;
            }
        }
    }

    public enum TaskStatus
    {
        NotStarted,
        Running,
        Completed,
        Cancelled,
        Error
    }

    public static class NotifyPropertyChangedExtention
    {
        public static void Raise<T, TP>(this PropertyChangedEventHandler pc, T source, Expression<Func<T, TP>> pe)
        {
            if (pc != null)
            {
                pc.Invoke(source, new PropertyChangedEventArgs(((MemberExpression)pe.Body).Member.Name));
            }
        }
    }

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

public class FileManager
    {
        public ObservableCollection<File> ListOfFiles { get; set; }

        public void AddFile(string fileName)
        {
            var file = new File(fileName);
            file.PropertyChanged += FilePropertyChanged;
            file.StartTask();
            ListOfFiles.Add(file);
        }

        void FilePropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "TaskStatus")
            {
                var file = (File) sender;
                if (file.TaskStatus==TaskStatus.Completed)
                {
                    RemoveFile(file);// ??? automatically remove file from list on completion??
                }
            }
        }

        public void RemoveFile(File file)
        {
            if (file.TaskStatus == TaskStatus.Running)
            {
                file.CancelTask();
            }
            //unbind event
            file.PropertyChanged -= FilePropertyChanged;
            ListOfFiles.Remove(file);
        }
    }

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.


Perhaps others can come up with the cleaner design you're looking for, but I wonder if the problems you're having are multi-threading issues, not inherent design flaws. I actually kind of like the idea of using a singleton to manage the list, but have it raise events for any changes (an ObservableCollection comes to mind here) which would notify any models or VMs subscribing to those events. Use Dispatcher to manage thread syncing, etc. for you when subscribing to these events. There's nothing preventing you from injecting your singleton instance into any models or VMs that need it.

The down side is managing what could become an eventing nightmare, but I wonder if any alternatives wouldn't have similar down sides.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜