Execute.OnUIThreadAndWait()

Oct 28, 2010 at 8:15 PM

I modified Execute to allow for waiting for completion of an action. This is helpful for when anonymous delegates affect local variables. Otherwise the UI thread might not get a chance to execute the code before the local variables are needed. Hope someone finds it useful...

public static class Execute
{
private static Action<System.Action, bool> executor = (action, wait) => action();

public static void InitializeWithDispatcher()
{
var dispatcher = Dispatcher.CurrentDispatcher;
executor = (action, wait) =>{
if (dispatcher.CheckAccess())
action();
else
{
if (wait)
dispatcher.Invoke(action);
else
dispatcher.BeginInvoke(action);
}
};
}

public static void OnUIThread(this System.Action action)
{
executor(action, false);
}

public static void OnUIThreadAndWait(this System.Action action)
{
executor(action, true);
}
}