Click here to Skip to main content
15,881,380 members
Articles / Desktop Programming / Windows Forms

Keep Your User Interface Responsive Easily Using a Coworker

Rate me:
Please Sign up or sign in to vote.
4.92/5 (12 votes)
8 Jul 2012CPOL7 min read 40.3K   1.1K   32  
An alternative approach to the new .NET async/await keywords to program asynchronously commands to make your user interface more responsive.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace AsyncModel
{
    /// <summary>
    /// A ICommand implementation that invokes an arbitrary method within a Coworker.SyncBlock to allow
    /// code not blocking the user interface to be run within Coworker.AsyncBlocks.
    /// </summary>
    public class SyncBlockCommand : ICommand
    {
        private readonly Action action;

        private bool isRunning;

        public SyncBlockCommand(Action action)
        {
            this.action = action;
        }

        #region ICommand Members

        public bool CanExecute(object parameter)
        {
            return !isRunning;
        }

        public event EventHandler CanExecuteChanged;

        private void RaiseCanExecuteChanged()
        {
            EventHandler eh = CanExecuteChanged;
            if( eh != null )
            {
                eh(this, EventArgs.Empty);
            }
        }

        public void Execute(object parameter)
        {
            if (CanExecute(parameter))
            {
                isRunning = true;
                RaiseCanExecuteChanged();
                Coworker.SyncBlock(() =>
                {
                    try
                    {
                        action();
                    }
                    finally
                    {
                        isRunning = false;
                        RaiseCanExecuteChanged();
                    }
                });
            }
        }

        #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 Code Project Open License (CPOL)


Written By
Software Developer
Sweden Sweden
Henrik Jonsson is a Microsoft Professional Certified Windows Developer (MCPD) that currently works as an IT consultant in Västerås, Sweden.

Henrik has worked in several small and large software development projects in various roles such as architect, developer, CM and tester.

He regularly reads The Code Project articles to keep updated about .NET development and get new ideas. He has contributed with articles presenting some useful libraries for Undo/Redo, Dynamic Linq Sorting and a Silverlight 5 MultiBinding solution.

Comments and Discussions