Execute.OnUIThread

Jan 17, 2011 at 11:08 PM

I noticed that the executor was recently updated to use Invoke instead of BeginInvoke. Here is a simple modification so that a developer has a choice...

 

/// <summary>
/// Initializes the framework using the current dispatcher.
/// </summary>
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);
		}
	};
}

/// <summary>
/// Executes the action on the UI thread and returns immediately.
/// </summary>
/// <param name="action">The action to execute.</param>
public static void OnUIThread(this System.Action action)
{
	executor(action, false);
}

/// <summary>
/// Executes the action on the UI thread and waits for it to complete.
/// </summary>
/// <param name="action">The action to execute.</param>
public static void OnUIThreadAndWait(this System.Action action)
{
	executor(action, true);
}

 

 

Jan 18, 2011 at 7:29 AM

I suppose that even using a default parameter value would suffice

/// <summary>
/// Executes the action on the UI thread and returns immediately.
/// </summary>
/// <param name="action">The action to execute.</param>
/// <param name="wait">If set to <c>true</c> the current thread will be be stopped until the action is executed.</param>
public static void OnUIThread(this System.Action action, bool wait = false)
{
	executor(action, wait);
}

Coordinator
Jan 18, 2011 at 2:21 PM

*If* I make a change, wait would have to be the default option in order to keep all code currently written working the same. We could have OnUIThread and BeginOnUIThread.

Jan 18, 2011 at 2:30 PM

You are right, I wrote 'wait' and thought 'async'. The default should match current behaviour.

The framework rarely needs to run code asynchronous to the Dispatcher, but such method can come in handy.

Jul 21, 2012 at 6:11 AM

This extension might be useful in some cases and wont hurt.

I suggest following signature:

public static void OnUIThreadAsync(this System.Action action)

What should happen if you call this from the UI thread?
Should the action also be queued with BeginInvoke(), as the method requests async execution explicitly?

Sep 2, 2012 at 1:51 PM

A pragmatic implementation of the async version:

 

static System.Action<System.Action> asyncExecutor = (action) => {
	try {
		Execute.OnUIThread(action);
	} catch (Exception ex) {
		LogManager.GetLog(typeof(Execute)).Error(ex);
	}
};

public static void OnUIThreadAsync(System.Action action) {
	asyncExecutor.BeginInvoke(action, asyncExecutor.EndInvoke, null);
}