Last active
August 29, 2015 13:56
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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