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

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;
using System.Linq;
using System.Windows.Input;

using Microsoft.Practices.Composite.Presentation.Properties;

namespace Microsoft.Practices.Composite.Presentation.Commands
{
    /// <summary>
    /// The CompositeCommand composites one or more ICommands.
    /// </summary>
    public partial class CompositeCommand : ICommand
    {
        private readonly List<ICommand> registeredCommands = new List<ICommand>();
        private List<WeakReference> _canExecuteChangedHandlers;
        private readonly bool monitorCommandActivity;
        private readonly EventHandler onRegisteredCommandCanExecuteChangedHandler;

        /// <summary>
        /// Initializes a new instance of <see cref="CompositeCommand"/>.
        /// </summary>
        public CompositeCommand()
        {
            this.onRegisteredCommandCanExecuteChangedHandler = new EventHandler(this.OnRegisteredCommandCanExecuteChanged);
        }

        /// <summary>
        /// Initializes a new instance of <see cref="CompositeCommand"/>.
        /// </summary>
        /// <param name="monitorCommandActivity">Indicates when the command activity is going to be monitored.</param>
        public CompositeCommand(bool monitorCommandActivity)
            : this()
        {
            this.monitorCommandActivity = monitorCommandActivity;
        }

        /// <summary>
        /// Adds a command to the collection and signs up for the <see cref="ICommand.CanExecuteChanged"/> event of it.
        /// </summary>
        ///  <remarks>
        /// If this command is set to monitor command activity, and <paramref name="command"/> 
        /// implements the <see cref="IActiveAware"/> interface, this method will subscribe to its
        /// <see cref="IActiveAware.IsActiveChanged"/> event.
        /// </remarks>
        /// <param name="command">The command to register.</param>
        public virtual void RegisterCommand(ICommand command)
        {
            if (command == this)
            {
                throw new ArgumentException(Resources.CannotRegisterCompositeCommandInItself);
            }

            lock (this.registeredCommands)
            {
                if (this.registeredCommands.Contains(command))
                {
                    throw new InvalidOperationException(Resources.CannotRegisterSameCommandTwice);
                }
                this.registeredCommands.Add(command);
            }

            command.CanExecuteChanged += this.onRegisteredCommandCanExecuteChangedHandler;
            this.OnCanExecuteChanged();

            if (this.monitorCommandActivity)
            {
                var activeAwareCommand = command as IActiveAware;
                if (activeAwareCommand != null)
                {
                    activeAwareCommand.IsActiveChanged += this.Command_IsActiveChanged;
                }
            }
        }

        /// <summary>
        /// Removes a command from the collection and removes itself from the <see cref="ICommand.CanExecuteChanged"/> event of it.
        /// </summary>
        /// <param name="command">The command to unregister.</param>
        public virtual void UnregisterCommand(ICommand command)
        {
            bool removed;
            lock (this.registeredCommands)
            {
                removed = this.registeredCommands.Remove(command);
            }

            if (removed)
            {
                command.CanExecuteChanged -= this.onRegisteredCommandCanExecuteChangedHandler;
                this.OnCanExecuteChanged();

                if (this.monitorCommandActivity)
                {
                    var activeAwareCommand = command as IActiveAware;
                    if (activeAwareCommand != null)
                    {
                        activeAwareCommand.IsActiveChanged -= this.Command_IsActiveChanged;
                    }
                }
            }
        }

        private void OnRegisteredCommandCanExecuteChanged(object sender, EventArgs e)
        {
            this.OnCanExecuteChanged();
        }

        /// <summary>
        /// Forwards <see cref="ICommand.CanExecute"/> to the registered commands and returns
        /// <see langword="true" /> if all of the commands return <see langword="true" />.
        /// </summary>
        /// <param name="parameter">Data used by the command.
        /// If the command does not require data to be passed, this object can be set to <see langword="null" />.
        /// </param>
        /// <returns><see langword="true" /> if all of the commands return <see langword="true" />; otherwise, <see langword="false" />.</returns>
        public virtual bool CanExecute(object parameter)
        {
            bool hasEnabledCommandsThatShouldBeExecuted = false;

            ICommand[] commandList;
            lock (this.registeredCommands)
            {
                commandList = this.registeredCommands.ToArray();
            }
            foreach (ICommand command in commandList)
            {
                if (this.ShouldExecute(command))
                {
                    if (!command.CanExecute(parameter))
                    {
                        return false;
                    }

                    hasEnabledCommandsThatShouldBeExecuted = true;
                }
            }

            return hasEnabledCommandsThatShouldBeExecuted;
        }

        /// <summary>
        /// Occurs when any of the registered commands raise <see cref="ICommand.CanExecuteChanged"/>. You must keep a hard
        /// reference to the handler to avoid garbage collection and unexpected results. See remarks for more information.
        /// </summary>
        /// <remarks>
        /// When subscribing to the <see cref="ICommand.CanExecuteChanged"/> event using 
        /// code (not when binding using XAML) will need to keep a hard reference to the event handler. This is to prevent 
        /// garbage collection of the event handler because the command implements the Weak Event pattern so it does not have
        /// a hard reference to this handler. An example implementation can be seen in the CompositeCommand and CommandBehaviorBase
        /// classes. In most scenarios, there is no reason to sign up to the CanExecuteChanged event directly, but if you do, you
        /// are responsible for maintaining the reference.
        /// </remarks>
        /// <example>
        /// The following code holds a reference to the event handler. The myEventHandlerReference value should be stored
        /// in an instance member to avoid it from being garbage collected.
        /// <code>
        /// EventHandler myEventHandlerReference = new EventHandler(this.OnCanExecuteChanged);
        /// command.CanExecuteChanged += myEventHandlerReference;
        /// </code>
        /// </example>
        public event EventHandler CanExecuteChanged
        {
            add
            {
                WeakEventHandlerManager.AddWeakReferenceHandler(ref _canExecuteChangedHandlers, value, 2);
            }
            remove
            {
                WeakEventHandlerManager.RemoveWeakReferenceHandler(_canExecuteChangedHandlers, value);
            }
        }

        /// <summary>
        /// Forwards <see cref="ICommand.Execute"/> to the registered commands.
        /// </summary>
        /// <param name="parameter">Data used by the command.
        /// If the command does not require data to be passed, this object can be set to <see langword="null" />.
        /// </param>
        public virtual void Execute(object parameter)
        {
            Queue<ICommand> commands;
            lock (this.registeredCommands)
            {
                commands = new Queue<ICommand>(this.registeredCommands.Where(this.ShouldExecute).ToList());
            }

            while (commands.Count > 0)
            {
                ICommand command = commands.Dequeue();
                command.Execute(parameter);
            }
        }

        /// <summary>
        /// Evaluates if a command should execute.
        /// </summary>
        /// <param name="command">The command to evaluate.</param>
        /// <returns>A <see cref="bool"/> value indicating whether the command should be used 
        /// when evaluating <see cref="CompositeCommand.CanExecute"/> and <see cref="CompositeCommand.Execute"/>.</returns>
        /// <remarks>
        /// If this command is set to monitor command activity, and <paramref name="command"/>
        /// implements the <see cref="IActiveAware"/> interface, 
        /// this method will return <see langword="false" /> if the command's <see cref="IActiveAware.IsActive"/> 
        /// property is <see langword="false" />; otherwise it always returns <see langword="true" />.</remarks>
        protected virtual bool ShouldExecute(ICommand command)
        {
            var activeAwareCommand = command as IActiveAware;

            if (this.monitorCommandActivity && activeAwareCommand != null)
            {
                return activeAwareCommand.IsActive;
            }

            return true;
        }

        /// <summary>
        /// Gets the list of all the registered commands.
        /// </summary>
        /// <value>A list of registered commands.</value>
        /// <remarks>This returns a copy of the commands subscribed to the CompositeCommand.</remarks>
        public IList<ICommand> RegisteredCommands
        {
            get
            {
                IList<ICommand> commandList;
                lock (this.registeredCommands)
                {
                    commandList = this.registeredCommands.ToList();
                }

                return commandList;
            }
        }

        /// <summary>
        /// Raises <see cref="ICommand.CanExecuteChanged"/> on the UI thread so every 
        /// command invoker can requery <see cref="ICommand.CanExecute"/> to check if the
        /// <see cref="CompositeCommand"/> can execute.
        /// </summary>
        protected virtual void OnCanExecuteChanged()
        {
            WeakEventHandlerManager.CallWeakReferenceHandlers(this, _canExecuteChangedHandlers);
        }


        /// <summary>
        /// Handler for IsActiveChanged events of registered commands.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">EventArgs to pass to the event.</param>
        private void Command_IsActiveChanged(object sender, EventArgs e)
        {
            this.OnCanExecuteChanged();
        }
    }
}

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 cofounder 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, and Windows Phone.
 
Daniel is the author of Windows Phone 7.5 Unleashed and Windows Phone 8 Unleashed, both published by SAMS.
 
Daniel is also the creator of a number of 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
Web04 | 2.8.140821.2 | Last Updated 1 May 2010
Article Copyright 2010 by Daniel Vaughan
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid