|
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.
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.