下面的 C# 代码
public async Task<T> GetValueOrCreateAsync<T>(string key, Func<T> factory)
{
//..
var value = await factory();
}
编译时会报错
CS1061 'Func<T>' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'Func<T>' could be found (are you missing a using directive or an assembly reference?)
public async Task<T> GetValueOrCreateAsync<T>(string key, Func<Task<T>> factory)
{
//..
var value = await factory();
return default(T);
}
Func<T> - > Func<Task<T>>
public static class FuncExtensions
{
public static TaskAwaiter<TResult> GetAwaiter<TResult>(this Func<TResult> function)
{
Task<TResult> task = new Task<TResult>(function);
task.Start();
return task.GetAwaiter();
}
}
return Task<T>.Run(func);