Skip to content

Instantly share code, notes, and snippets.

@scionwest
Created August 16, 2015 00:36
Show Gist options
  • Save scionwest/829572d3268fb34bec3d to your computer and use it in GitHub Desktop.
Save scionwest/829572d3268fb34bec3d to your computer and use it in GitHub Desktop.
/// <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)
{
// I want to replace this....
Task.Run(this.StartAsync)
.ContinueWith(task => startCompletedCallback(this), TaskScheduler.FromCurrentSynchronizationContext());
// With this, having the callback invoked from within Start() on the current sync context.
Task.Run(this.Start(startCompletedCallback));
}
/// <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(Action<IGame> endStartCallback = null)
{
foreach (IAdapter adapter in this.initializedAdapters)
{
await adapter.Start(this);
}
this.IsRunning = true;
if (endStartCallback != null)
{
endStartCallback(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