Created
January 30, 2019 14:48
-
-
Save ArtemAvramenko/8eff3e4a46ae78114012bf95cf8aebc8 to your computer and use it in GitHub Desktop.
C# run async method synchronously
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
public static class AsyncHelper | |
{ | |
public static T RunSync<T>(Func<Task<T>> action) | |
{ | |
try | |
{ | |
var result = default(T); | |
Task.Run(async () => | |
{ | |
result = await action(); | |
}).Wait(); | |
return result; | |
} | |
catch (AggregateException ex) | |
{ | |
throw ex.InnerException; | |
} | |
} | |
public static void RunSync(Func<Task> action) | |
{ | |
RunSync(async () => | |
{ | |
await action(); | |
return false; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment