Microsoft Identity具有扩展方法,这些扩展方法可以同步调用异步方法。例如,有GenerateUserIdentityAsync()方法和相等的CreateIdentity()
如果查看UserManagerExtensions.CreateIdentity(),它看起来像这样:
public static ClaimsIdentity CreateIdentity<TUser, TKey>(this UserManager<TUser, TKey> manager, TUser user,
string authenticationType)
where TKey : IEquatable<TKey>
where TUser : class, IUser<TKey>
{
if (manager == null)
{
throw new ArgumentNullException("manager");
}
return AsyncHelper.RunSync(() => manager.CreateIdentityAsync(user, authenticationType));
}
现在让我们看看AsyncHelper.RunSync的作用
public static TResult RunSync<TResult>(Func<Task<TResult>> func)
{
var cultureUi = CultureInfo.CurrentUICulture;
var culture = CultureInfo.CurrentCulture;
return _myTaskFactory.StartNew(() =>
{
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = cultureUi;
return func();
}).Unwrap().GetAwaiter().GetResult();
}
因此,这是异步方法的包装器。并且请不要从Result中读取数据-它可能会阻塞ASP中的代码。
还有另一种方式-对我来说很可疑,但是您也可以考虑
Result r = null;
YourAsyncMethod()
.ContinueWith(t =>
{
r = t.Result;
})
.Wait();