我正在更新一个库,该库具有一个在.NET3.5中构建的API图面.因此,所有方法都是同步的.我不能更改API(即,将返回值转换为Task),因为这将需要更改所有调用方.因此,留给我的是如何以同步的方式最好地调用异步方法.这是在ASP.NET 4、ASP.NET Core和.NET/.NET Core控制台应用程序的上下文中进行的.
我可能还不够清楚-情况是我有不支持异步的现有代码,我想使用仅支持异步方法的新库,如System.Net.Http和AWS SDK.因此,我需要弥合这一鸿沟,并且能够拥有可以同步调用但随后可以在其他地方调用异步方法的代码.
我做了很多阅读,这个问题被问了很多次,也回答了很多次.
Calling async method from non async method个
Synchronously waiting for an async operation, and why does Wait() freeze the program here
Calling an async method from a synchronous method
How would I run an async Task<T> method synchronously?
Calling async method synchronously个
How to call asynchronous method from synchronous method in C#?
问题是大多数答案都不一样!我见过的最常见的方法是使用.结果,但这可能会导致死锁.我已经try 了以下所有方法,它们都很有效,但我不确定哪种方法是避免死锁、具有良好性能并能很好地配合运行时的最佳方法(在尊重任务调度器、任务创建选项等方面).有明确的答案吗?最好的方法是什么?
private static T taskSyncRunner<T>(Func<Task<T>> task)
{
T result;
// approach 1
result = Task.Run(async () => await task()).ConfigureAwait(false).GetAwaiter().GetResult();
// approach 2
result = Task.Run(task).ConfigureAwait(false).GetAwaiter().GetResult();
// approach 3
result = task().ConfigureAwait(false).GetAwaiter().GetResult();
// approach 4
result = Task.Run(task).Result;
// approach 5
result = Task.Run(task).GetAwaiter().GetResult();
// approach 6
var t = task();
t.RunSynchronously();
result = t.Result;
// approach 7
var t1 = task();
Task.WaitAll(t1);
result = t1.Result;
// approach 8?
return result;
}