Click here to Skip to main content
Click here to Skip to main content
 
Add your own
alternative version
Go to top

Introducing the Model Thread View Thread Pattern

, 1 May 2010
Reduce threading code, and increase UI responsiveness with a new pattern extending MVVM.
Mtvt_2010_5_1__12_15.zip
Libraries
DanielVaughan
DanielVaughan.Silverlight.dll
DanielVaughan.Silverlight.pdb
Microsoft.Practices.ServiceLocation.dll
Microsoft.Practices.Unity.dll
System.ServiceModel.PollingDuplex.dll
System.Xml.Linq.dll
Prism
Silverlight
Microsoft.Practices.Composite.dll
Microsoft.Practices.Composite.pdb
Microsoft.Practices.Composite.Presentation.dll
Microsoft.Practices.Composite.Presentation.pdb
Microsoft.Practices.ServiceLocation.dll
System.Windows.Controls.dll
Mtvt
DanielVaughan.Mtvt.suo
DanielVaughan.Mtvt.vsmdi
Local.testsettings
TraceAndTestImpact.testsettings
DanielVaughan.MtvtExample
Bin
Debug
ar
bg
ca
cs
da
de
el
es
et
eu
fi
fr
he
hr
hu
id
it
ja
ko
lt
lv
ms
nl
no
pl
Properties
pt
pt-BR
ro
ru
sk
sl
sr-Cyrl-CS
sr-Latn-CS
sv
th
tr
uk
vi
zh-Hans
zh-Hant
Release
Collections
CommandModel
ComponentModel
Concurrency
Diagrams
OverviewDiagram.cd
Images
WpfDisciplesBanner.png
obj
Debug
DanielVaughan.MtvtExample.g.resources
DesignTimeResolveAssemblyReferences.cache
DesignTimeResolveAssemblyReferencesInput.cache
TempPE
Properties
Service References
UIModel
DanielVaughan.MtvtExample.Tests
Bin
Debug
ar
bg
ca
cs
da
de
el
es
et
eu
fi
fr
he
hr
hu
id
it
ja
ko
lt
lv
ms
nl
no
pl
Properties
pt
pt-BR
ro
ru
sk
sl
sr-Cyrl-CS
sr-Latn-CS
sv
th
tr
uk
vi
zh-Hans
zh-Hant
Release
Mocks
obj
Debug
DanielVaughan.MtvtExample.Tests.g.resources
DesignTimeResolveAssemblyReferencesInput.cache
ResolveAssemblyReference.cache
TempPE
Properties
DanielVaughan.MtvtExample.Web
bin
ClientBin
obj
Debug
DesignTimeResolveAssemblyReferencesInput.cache
TempPE
Properties
Prism
CAL
CAL.vsmdi
CompositeApplicationLibrary.4.5.resharper.user
CompositeApplicationLibrary_Desktop.4.5.resharper.user
LocalTestRun.testrunconfig
Desktop
Composite
OpenSource.snk
bin
Events
Logging
Modularity
obj
Debug
Composite.Desktop.csproj.GenerateResource.Cache
Microsoft.Practices.Composite.dll
Microsoft.Practices.Composite.pdb
Microsoft.Practices.Composite.Properties.Resources.resources
ResolveAssemblyReference.cache
TempPE
Release
Composite.Desktop.csproj.GenerateResource.Cache
Microsoft.Practices.Composite.dll
Microsoft.Practices.Composite.pdb
Microsoft.Practices.Composite.Properties.Resources.resources
TempPE
Properties.Resources.Designer.cs.dll
Properties
Regions
Composite.Presentation
OpenSource.snk
bin
Commands
Events
obj
Debug
Composite.Presentation.Desktop.csproj.GenerateResource.Cache
Microsoft.Practices.Composite.Presentation.dll
Microsoft.Practices.Composite.Presentation.pdb
Microsoft.Practices.Composite.Presentation.Properties.Resources.resources
ResolveAssemblyReference.cache
TempPE
Release
Composite.Presentation.Desktop.csproj.GenerateResource.Cache
Microsoft.Practices.Composite.Presentation.dll
Microsoft.Practices.Composite.Presentation.pdb
Microsoft.Practices.Composite.Presentation.Properties.Resources.resources
ResolveAssemblyReference.cache
TempPE
Properties.Resources.Designer.cs.dll
Properties
Regions
Behaviors
Silverlight
Composite
Composite.Silverlight.csproj.user
Migrated rules for Composite.Silverlight.ruleset
Bin
Events
Logging
Modularity
obj
Debug
Composite.Silverlight.csproj.GenerateResource.Cache
DesignTimeResolveAssemblyReferencesInput.cache
Microsoft.Practices.Composite.dll
Microsoft.Practices.Composite.pdb
Microsoft.Practices.Composite.Properties.Resources.resources
ResGen.read.1.tlog
ResGen.write.1.tlog
ResolveAssemblyReference.cache
TempPE
Properties.Resources.Designer.cs.dll
Release
Composite.Silverlight.csproj.GenerateResource.Cache
Microsoft.Practices.Composite.dll
Microsoft.Practices.Composite.pdb
Microsoft.Practices.Composite.Properties.Resources.resources
TempPE
Properties
Regions
Composite.Presentation
Composite.Presentation.Silverlight.csproj.user
Migrated rules for Composite.Presentation.Silverlight.ruleset
Bin
Commands
Events
obj
Debug
build.force
Composite.Presentation.Silverlight.csproj.GenerateResource.Cache
DesignTimeResolveAssemblyReferencesInput.cache
Microsoft.Practices.Composite.Presentation.dll
Microsoft.Practices.Composite.Presentation.pdb
Microsoft.Practices.Composite.Presentation.Properties.Resources.resources
ResGen.read.1.tlog
ResGen.write.1.tlog
ResolveAssemblyReference.cache
TempPE
Release
Composite.Presentation.Silverlight.csproj.GenerateResource.Cache
Microsoft.Practices.Composite.Presentation.dll
Microsoft.Practices.Composite.Presentation.pdb
Microsoft.Practices.Composite.Presentation.Properties.Resources.resources
ResolveAssemblyReference.cache
TempPE
Properties
Regions
Behaviors
LIB
Silverlight
ServiceLocation
Microsoft.Practices.ServiceLocation.dll
//===================================================================================
// Microsoft patterns & practices
// Composite Application Guidance for Windows Presentation Foundation and Silverlight
//===================================================================================
// Copyright (c) Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===================================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===================================================================================
using System;
using System.Collections.Generic;

namespace Microsoft.Practices.Composite
{
    /// <summary>
    /// A dictionary of lists.
    /// </summary>
    /// <typeparam name="TKey">The key to use for lists.</typeparam>
    /// <typeparam name="TValue">The type of the value held by lists.</typeparam>
    public sealed class ListDictionary<TKey, TValue> : IDictionary<TKey, IList<TValue>>
    {
        Dictionary<TKey, IList<TValue>> innerValues = new Dictionary<TKey, IList<TValue>>();

        #region Public Methods

        /// <summary>
        /// If a list does not already exist, it will be created automatically.
        /// </summary>
        /// <param name="key">The key of the list that will hold the value.</param>
        public void Add(TKey key)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            CreateNewList(key);
        }

        /// <summary>
        /// Adds a value to a list with the given key. If a list does not already exist, 
        /// it will be created automatically.
        /// </summary>
        /// <param name="key">The key of the list that will hold the value.</param>
        /// <param name="value">The value to add to the list under the given key.</param>
        public void Add(TKey key, TValue value)
        {
            if (key == null)

                throw new ArgumentNullException("key");
            if (value == null)

                throw new ArgumentNullException("value");

            if (innerValues.ContainsKey(key))
            {
                innerValues[key].Add(value);
            }
            else
            {
                List<TValue> values = CreateNewList(key);
                values.Add(value);
            }
        }

        private List<TValue> CreateNewList(TKey key)
        {
            List<TValue> values = new List<TValue>();
            innerValues.Add(key, values);

            return values;
        }

        /// <summary>
        /// Removes all entries in the dictionary.
        /// </summary>
        public void Clear()
        {
            innerValues.Clear();
        }

        /// <summary>
        /// Determines whether the dictionary contains the specified value.
        /// </summary>
        /// <param name="value">The value to locate.</param>
        /// <returns>true if the dictionary contains the value in any list; otherwise, false.</returns>
        public bool ContainsValue(TValue value)
        {
            foreach (KeyValuePair<TKey, IList<TValue>> pair in innerValues)
            {
                if (pair.Value.Contains(value))
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// Determines whether the dictionary contains the given key.
        /// </summary>
        /// <param name="key">The key to locate.</param>
        /// <returns>true if the dictionary contains the given key; otherwise, false.</returns>
        public bool ContainsKey(TKey key)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            return innerValues.ContainsKey(key);
        }

        /// <summary>
        /// Retrieves the all the elements from the list which have a key that matches the condition 
        /// defined by the specified predicate.
        /// </summary>
        /// <param name="keyFilter">The filter with the condition to use to filter lists by their key.</param>
        /// <returns>The elements that have a key that matches the condition defined by the specified predicate.</returns>
        public IEnumerable<TValue> FindAllValuesByKey(Predicate<TKey> keyFilter)
        {
            foreach (KeyValuePair<TKey, IList<TValue>> pair in this)
            {
                if (keyFilter(pair.Key))
                {
                    foreach (TValue value in pair.Value)
                    {
                        yield return value;
                    }
                }
            }
        }

        /// <summary>
        /// Retrieves all the elements that match the condition defined by the specified predicate.
        /// </summary>
        /// <param name="valueFilter">The filter with the condition to use to filter values.</param>
        /// <returns>The elements that match the condition defined by the specified predicate.</returns>
        public IEnumerable<TValue> FindAllValues(Predicate<TValue> valueFilter)
        {
            foreach (KeyValuePair<TKey, IList<TValue>> pair in this)
            {
                foreach (TValue value in pair.Value)
                {
                    if (valueFilter(value))
                    {
                        yield return value;
                    }
                }
            }
        }

        /// <summary>
        /// Removes a list by key.
        /// </summary>
        /// <param name="key">The key of the list to remove.</param>
        /// <returns><see langword="true" /> if the element was removed.</returns>
        public bool Remove(TKey key)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            return innerValues.Remove(key);
        }

        /// <summary>
        /// Removes a value from the list with the given key.
        /// </summary>
        /// <param name="key">The key of the list where the value exists.</param>
        /// <param name="value">The value to remove.</param>
        public void Remove(TKey key, TValue value)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            if (value == null)
                throw new ArgumentNullException("value");

            if (innerValues.ContainsKey(key))
            {
                List<TValue> innerList = (List<TValue>)innerValues[key];
                innerList.RemoveAll(delegate(TValue item)
                                               {
                                                   return value.Equals(item);
                                               });
            }
        }

        /// <summary>
        /// Removes a value from all lists where it may be found.
        /// </summary>
        /// <param name="value">The value to remove.</param>
        public void Remove(TValue value)
        {
            foreach (KeyValuePair<TKey, IList<TValue>> pair in innerValues)
            {
                Remove(pair.Key, value);
            }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets a shallow copy of all values in all lists.
        /// </summary>
        /// <value>List of values.</value>
        public IList<TValue> Values
        {
            get
            {
                List<TValue> values = new List<TValue>();
                foreach (IEnumerable<TValue> list in innerValues.Values)
                {
                    values.AddRange(list);
                }

                return values;
            }
        }

        /// <summary>
        /// Gets the list of keys in the dictionary.
        /// </summary>
        /// <value>Collection of keys.</value>
        public ICollection<TKey> Keys
        {
            get { return innerValues.Keys; }
        }

        /// <summary>
        /// Gets or sets the list associated with the given key. The 
        /// access always succeeds, eventually returning an empty list.
        /// </summary>
        /// <param name="key">The key of the list to access.</param>
        /// <returns>The list associated with the key.</returns>
        public IList<TValue> this[TKey key]
        {
            get
            {
                if (innerValues.ContainsKey(key) == false)
                {
                    innerValues.Add(key, new List<TValue>());
                }
                return innerValues[key];
            }
            set { innerValues[key] = value; }
        }

        /// <summary>
        /// Gets the number of lists in the dictionary.
        /// </summary>
        /// <value>Value indicating the values count.</value>
        public int Count
        {
            get { return innerValues.Count; }
        }

        #endregion

        #region IDictionary<TKey,List<TValue>> Members

        /// <summary>
        /// See <see cref="IDictionary{TKey,TValue}.Add"/> for more information.
        /// </summary>
        void IDictionary<TKey, IList<TValue>>.Add(TKey key, IList<TValue> value)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            if (value == null)
                throw new ArgumentNullException("value");

            innerValues.Add(key, value);
        }

        /// <summary>
        /// See <see cref="IDictionary{TKey,TValue}.TryGetValue"/> for more information.
        /// </summary>
        bool IDictionary<TKey, IList<TValue>>.TryGetValue(TKey key, out IList<TValue> value)
        {
            value = this[key];
            return true;
        }

        /// <summary>
        /// See <see cref="IDictionary{TKey,TValue}.Values"/> for more information.
        /// </summary>
        ICollection<IList<TValue>> IDictionary<TKey, IList<TValue>>.Values
        {
            get { return innerValues.Values; }
        }

        #endregion

        #region ICollection<KeyValuePair<TKey,List<TValue>>> Members

        /// <summary>
        /// See <see cref="ICollection{TValue}.Add"/> for more information.
        /// </summary>
        void ICollection<KeyValuePair<TKey, IList<TValue>>>.Add(KeyValuePair<TKey, IList<TValue>> item)
        {
            ((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).Add(item);
        }

        /// <summary>
        /// See <see cref="ICollection{TValue}.Contains"/> for more information.
        /// </summary>
        bool ICollection<KeyValuePair<TKey, IList<TValue>>>.Contains(KeyValuePair<TKey, IList<TValue>> item)
        {
            return ((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).Contains(item);
        }

        /// <summary>
        /// See <see cref="ICollection{TValue}.CopyTo"/> for more information.
        /// </summary>
        void ICollection<KeyValuePair<TKey, IList<TValue>>>.CopyTo(KeyValuePair<TKey, IList<TValue>>[] array, int arrayIndex)
        {
            ((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).CopyTo(array, arrayIndex);
        }

        /// <summary>
        /// See <see cref="ICollection{TValue}.IsReadOnly"/> for more information.
        /// </summary>
        bool ICollection<KeyValuePair<TKey, IList<TValue>>>.IsReadOnly
        {
            get { return ((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).IsReadOnly; }
        }

        /// <summary>
        /// See <see cref="ICollection{TValue}.Remove"/> for more information.
        /// </summary>
        bool ICollection<KeyValuePair<TKey, IList<TValue>>>.Remove(KeyValuePair<TKey, IList<TValue>> item)
        {
            return ((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).Remove(item);
        }

        #endregion

        #region IEnumerable<KeyValuePair<TKey,List<TValue>>> Members

        /// <summary>
        /// See <see cref="IEnumerable{TValue}.GetEnumerator"/> for more information.
        /// </summary>
        IEnumerator<KeyValuePair<TKey, IList<TValue>>> IEnumerable<KeyValuePair<TKey, IList<TValue>>>.GetEnumerator()
        {
            return innerValues.GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        /// <summary>
        /// See <see cref="System.Collections.IEnumerable.GetEnumerator"/> for more information.
        /// </summary>
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return innerValues.GetEnumerator();
        }

        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The BSD License

Share

About the Author

Daniel Vaughan
President Outcoder
Switzerland Switzerland
Daniel Vaughan is a Microsoft MVP and co-founder of Outcoder, a Swiss software and consulting company dedicated to creating best-of-breed user experiences and leading-edge back-end solutions, using the Microsoft stack of technologies--in particular WPF, WinRT, Windows Phone, and also Xamarin.Forms.
 
Daniel is the author of Windows Phone 8 Unleashed and Windows Phone 7.5 Unleashed, both published by SAMS.
 
Daniel is the developer behind several acclaimed Windows Phone apps including Surfy, Intellicam, and Splashbox; and is the creator of a number of popular open-source projects including Calcium SDK, and Clog.
 
Would you like Daniel to bring value to your organisation? Please contact

Daniel's Blog | MVP profile | Follow on Twitter
 
Windows Phone Experts
Follow on   Twitter   Google+   LinkedIn

| Advertise | Privacy | Mobile
Web02 | 2.8.140926.1 | Last Updated 1 May 2010
Article Copyright 2010 by Daniel Vaughan
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid