Skip to content

Instantly share code, notes, and snippets.

@DamianSuess
Created March 25, 2021 22:00
Show Gist options
  • Save DamianSuess/44f0433840e1b9ec24d3ea2a2b296db9 to your computer and use it in GitHub Desktop.
Save DamianSuess/44f0433840e1b9ec24d3ea2a2b296db9 to your computer and use it in GitHub Desktop.
Await in a Non-Async Method
// Sample 1 - Non-Helper Function Method
public bool HardReset()
{
return HardResetAsync().GetAwaiter().GetResult();
}
public async Task<bool> HardResetAsync()
{
// Real code goes here
await Task.Yield();
return true;
}
// ---------------------------
// Sample 2 - Helper Functions
public static TResult RunSync<TResult>(Func<Task<TResult>> method)
{
var task = method();
return task.GetAwaiter().GetResult();
}
public static void RunSync(Func<Task> method)
{
var task = method();
task.GetAwaiter().GetResult();
}
// Usage -----------------
public bool DoSomething()
{
var result = RunSync(() => SomethingAsync());
}
public async bool SomethingAsync()
{
// Real awaitable code goes here
await Task.Yield();
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment