-
-
Save jakesays-old/6ea8cd2c24f3261fb88a to your computer and use it in GitHub Desktop.
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
class Callbacker | |
{ | |
public SynchronizationContext Context{get;private set;} | |
public Action<IGame> Callback{get;private set;} | |
public Callbacker(SynchronizationContext context, Action<IGame> callback) | |
{ | |
Context = context; | |
Callback = callback; | |
} | |
private void ContextHandler(object game) | |
{ | |
Callback((IGame) game); | |
} | |
public void Invoke(IGame game) | |
{ | |
Context.Post(ContextHandler, game); | |
} | |
} | |
/// <summary> | |
/// Starts the game using the begin/end async pattern. This method requires the caller to handle the process life-cycle management as a loop is not generated internally. | |
/// </summary> | |
/// <param name="startCompletedCallback">The delegate to invoke when the game startup has completed.</param> | |
public void BeginStart(Action<IGame> startCompletedCallback) | |
{ | |
var callbacker = new Callbacker(SynchronizationContext.Current, startCompletedCallback); | |
// With this, having the callback invoked from within Start() on the current sync context. | |
Task.Run(this.Start(callbacker)); | |
} | |
/// <summary> | |
/// Starts game asynchronously. This will start a game loop that can be awaited. The loop will run until stopped. | |
/// </summary> | |
/// <returns>Returns an awaitable Task</returns> | |
public async Task StartAsync() | |
{ | |
await this.Start(); | |
} | |
private async Task Start(Callbacker callbacker = null) | |
{ | |
foreach (IAdapter adapter in this.initializedAdapters) | |
{ | |
await adapter.Start(this); | |
} | |
this.IsRunning = true; | |
if (callbacker != null) | |
{ | |
callbacker.Invoke(this); | |
return; | |
} | |
// Start the game loop. | |
await Task.Run(() => | |
{ | |
while (this.IsRunning) | |
{ | |
Task.Delay(1).Wait(); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment