Created
          March 25, 2021 22:00 
        
      - 
      
- 
        Save DamianSuess/44f0433840e1b9ec24d3ea2a2b296db9 to your computer and use it in GitHub Desktop. 
    Await in a Non-Async Method
  
        
  
    
      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
    
  
  
    
  | // 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