Skip to content

Instantly share code, notes, and snippets.

@dgroft
Last active August 29, 2015 13:56
Show Gist options
  • Save dgroft/9057591 to your computer and use it in GitHub Desktop.
Save dgroft/9057591 to your computer and use it in GitHub Desktop.
Asynchronously invoke a lambda and invoke a callback lambda upon completion back on the main thread. Helpful in the event you're unable to enjoy TPL or async/await.
using System.Runtime.Remoting.Messaging;
using System.Threading;
// capture the ui thread context for completion callback
private SynchronizationContext context = SynchronizationContext.Current;
Action action = () => {
/* do some stuff */
};
Action<IAsyncResult> complete = (result) => {
try
{
Action caller = (Action)((AsyncResult)result).AsyncDelegate;
caller.EndInvoke(result);
context.Post(state => {
/* do this stuff back on main thread */
}, null);
}
catch (Exception ex)
{
/* do some error handling */
}
};
action.BeginInvoke(new AsyncCallback(complete), null);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment