这个问题在这里已经有了答案:
How would I run an async Task<T> method synchronously?
(25 个回答)
3个月前关闭。
在我的其中之一 IDatabaseInitializer
在 Seed
给我的方法 DbContext
我将初始数据插入数据库。除其他外,还有一些用户需要初始化。但据我使用 Microsoft.AspNet.Identity.EntityFramework.UserStore
与 Microsoft.AspNet.Identity.UserManager
它只有异步方法 DbUpdateConcurrencyException
如下:
private static void CreateUser(DbContext context, string[] roles, string userName, string userEmail) {
// given context is
var user = new ApplicationUser { /* ... fields init */ };
var userStoreAdapter = new ApplicationUserRepository(context);
var manager = new UserManager<ApplicationUser>(userStoreAdapter);
// pass the creation to manager by calling it synchronously. See UserManagerExtensions
manager.Create(user, Domain.Constants.DefaultPassword);
manager.AddToRoles(user.Id, roles);
context.SaveChanges(); // throws DbUpdateConcurrencyException. See another approach below.
}
所以问题是是否有办法使用
UserManager
与 DbContext
没有并发问题?我尝试了以下来自 Optimistic Concurrency Patterns 的方法但这不会创建用户:
bool isSaved = true;
do
{
try
{
context.SaveChanges();
isSaved = true;
}
catch (DbUpdateConcurrencyException ex)
{
foreach (var entry in ex.Entries)
{
entry.Reload();
}
isSaved = false;
}
} while (!isSaved);
最佳答案
var result = Task.Run(() => {
/*whatever you want here*/
}).Result;
// Do whatever u want with the result after
关于c# - 如何同步使用 UserManager?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32847368/