Created
August 25, 2015 06:01
-
-
Save mattkruskamp/5228987c149df7a82982 to your computer and use it in GitHub Desktop.
.Net Problem: Async and Windowless Forms
This file contains hidden or 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; | |
using System.ComponentModel; | |
using System.Threading; | |
/// <summary> | |
/// Class that allows multithread syncronization | |
/// from asyncronous calls. Anything wrapped with | |
/// the syncronize method will be executed on the | |
/// same thread as where the AsyncSyncronizer | |
/// is instantiated. | |
/// </summary> | |
/// <example> | |
/// Instantiate on thread you want to use | |
/// AsyncSyncronizer sync = new AsyncSyncronizer(); | |
/// | |
/// // Run on the code you would like to execute. | |
/// this.sync.Syncronize( | |
/// delegate | |
/// { | |
/// /*Code to Execute*/ | |
/// }); | |
///</example> | |
public class AsyncSyncronizer | |
{ | |
/// <summary> | |
/// Delegate pointing to code executed | |
/// within the Syncronize method. | |
/// </summary> | |
public delegate void AsyncDelegate(); | |
/// <summary> | |
/// Async operation which will push execution | |
/// to the proper thread. | |
/// </summary> | |
private AsyncOperation operation; | |
/// <summary> | |
/// Creates an object of the AsyncSyncronizer | |
/// Everything wrapped within the Syncronize | |
/// method will be executed by default on the | |
/// thread this is instantiated on. In order to change | |
/// the thread, run SetThread. | |
/// </summary> | |
public AsyncSyncronizer() | |
{ | |
// Set to this thread. | |
this.SetThread(); | |
} | |
/// <summary> | |
/// Sets the thread code will by syncronized to | |
/// to the current thread running. | |
/// </summary> | |
public void SetThread() | |
{ | |
this.operation = | |
AsyncOperationManager.CreateOperation(null); | |
} | |
/// <summary> | |
/// Runs code within this method on the | |
/// thread either set by set thread or | |
/// where the object was instantiated. | |
/// </summary> | |
/// <param name=“render”>The code | |
/// to execute on the specified thread.</param> | |
public void Syncronize( | |
AsyncDelegate render) | |
{ | |
this.operation.Post(new SendOrPostCallback(delegate(object state) | |
{ | |
render(); | |
}), null); | |
this.operation.OperationCompleted(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment