using System;
using System.Globalization;
using System.Threading;
namespace DelftTools.Shell.Core.Workflow
{
///
/// AsynchActivityRunner is a composition of BackGroundWorker doing the job and the Activity to be done.
///
/// TODO: merge with ActivityRunner - YAGNI
///
public class AsyncActivityRunner
{
public event EventHandler Completed;
// private readonly BackgroundWorker backgroundWorker;
private readonly Action action;
private readonly CultureInfo uiCulture;
private readonly CultureInfo culture;
public AsyncActivityRunner(IActivity activity, Action action)
{
Activity = activity;
this.action = action;
uiCulture = Thread.CurrentThread.CurrentUICulture;
culture = Thread.CurrentThread.CurrentCulture;
}
public IActivity Activity { get; private set; }
///
/// A task completed succesfully if it ran without exceptions.
///
public bool CompletedSuccesfully { get; private set; }
public Exception Exception { get; set; }
// TODO: why do we need to pass activity and action here? Isn't it expected that task will always call Execute?
public void Run()
{
ThreadPool.QueueUserWorkItem(delegate { RunAction(); });
}
public void Cancel()
{
Activity.Cancel();
}
private void RunAction()
{
Thread.CurrentThread.CurrentUICulture = uiCulture;
Thread.CurrentThread.CurrentCulture = culture;
try
{
action(Activity);
CompletedSuccesfully = true;
}
catch (Exception e)
{
Exception = e;
CompletedSuccesfully = false;
}
if (Completed != null)
{
Completed(this, EventArgs.Empty);
}
}
}
}