Helper methods to run delegates on ui thread or on background thread
Usage:
Execute.OnUIThread(() => PropertyChanged(this, new PropertyChangedEventArgs(propertyName)));
And:
Execute.InBackground(() => SaveModel(),
exception =>
{
//HandleError()
});
Execute.InBackground(() => GetModel(),
(model, exception) =>
{
//HandleError & do something with model
});
The best thing about abstracting these to methods is that you can change behavior for these for unit tests (so that both run on the current thread).
Implementation:
public static class Execute
{
private static Action<Action> _uiThreadExecutor = action => action();
private static Action<Action> _backgroundExecutor = action => action();
public static void InitializeWithDispatcher()
{
var dispatcher = Dispatcher.CurrentDispatcher;
_uiThreadExecutor = action =>
{
if (dispatcher.CheckAccess())
action();
else
dispatcher.BeginInvoke(action);
};
_backgroundExecutor = action => ThreadPool.QueueUserWorkItem(obj => action());
}
public static void InBackground<TResult>(this Func<TResult> action, Action<TResult, Exception> callback)
{
_backgroundExecutor(() =>
{
Exception exception = null;
TResult result = default(TResult);
try
{
result = action();
}
catch (Exception ex)
{
exception = ex;
}
OnUIThread(() => callback(result, exception));
});
}
public static void InBackground(this Action action, Action<Exception> callback)
{
_backgroundExecutor(() =>
{
Exception exception = null;
try
{
action();
}
catch (Exception ex)
{
exception = ex;
}
OnUIThread(() => callback(exception));
});
}
public static void OnUIThread(this Action action)
{
_uiThreadExecutor(action);
}
}
As you can see the default delegates just execute the action directly, resulting in single thread behavior for unit tests. The InitializeWithDispatcher method is only run from the bootstrapper of the application (which is not run from unit tests).
Fork
1 Feedback
Cool - that's more or less the same thing I do. Using the dispatcher directly is pretty gross. - cstrahan Thursday 16, 2010 8:41 PMYou must log in before you can give any feedback
You must log in before you can post a comment


831
0



Mark 'c#' tag as 'like'
Mark 'c#' tag as 'ignore'