After hours of trying different methods, with more or less success, this is whatWell I ended with. It doesn't end in a deadlock while getting result and itwas using this approach for years, which also gets and throws the original exceptionhandles and notpropagates exceptions from the wrapped oneunderlying async task. Which works flawlessly.
private ReturnTypestring RunSync() { var task = Task.Run(async () => await myMethodAsyncGenerateCodeService.GenerateCodeAsync(agency)); if (task.IsFaulted && task.Exception != null) { throw task.Exception; } return task.Result; } But since that Microsoft created this async helper: https://github.com/aspnet/AspNetIdentity/blob/main/src/Microsoft.AspNet.Identity.Core/AsyncHelper.cs
Here is also their source:
public static void RunSync(Func<Task> func) { var cultureUi = CultureInfo.CurrentUICulture; var culture = CultureInfo.CurrentCulture; _myTaskFactory.StartNew(() => { Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = cultureUi; return func(); }).Unwrap().GetAwaiter().GetResult(); }