如何在ASP.NET中实现异步api?

时间:2015-08-07 16:02:35

标签: c# asp.net asynchronous async-await task

也许这被问了几百次但是:在我的网站上我希望能够添加/更新/验证/删除/检查用户是否存在并且异步这样做,所以这是怎么回事实施:

public class UserRepo 
 {
    public async Task<bool> Add(RegisterViewModel model)
    {
        return await Task.Run(async () =>
        {
            if (await Exists(model.UserName)) return false;

            using (var db = new DataConnection(provider, Context))
            {
                var users = db.GetTable<User>();

                db.Insert(new User()
                {
                    Username = model.UserName,
                    Password = model.Password
                });
            }

            return await Exists(model.UserName);
        });
    }

    public async Task<bool> Remove(int id)
    {
        return await Task.Run(async () =>
        {
            using (var db = new DataConnection(provider, Context))
            {
                var users = db.GetTable<User>();

                users.Where(x => x.Id == id).Delete();
                return users.Any(x => x.Id == id);
            }
        });
    }

    public async Task Update(User user)
    {
        await Task.Run(async () =>
        {
            if (!(await Exists(user.Username))) return;

            using (var db = new DataConnection(provider, Context))
            {
                db.Update(user);
            }
        });
    }

    public async Task<bool> Verify(LoginViewModel model)
    {
        await Task.Run(async () =>
        {
            using (var db = new DataConnection(provider, Context))
            {
                return db.GetTable<User>().Any(x => x.Username == username && x.Password == model.Password);
            }
        });
    }

    public async Task<bool> Exists(string username)
    {
        return await Task.Run(async () =>
        {
            using (var db = new DataConnection(provider, Context))
            {
                return db.GetTable<User>().Any(x => x.Username == username);
            }
        });
    }
 }

虽然它有效但老实说我还是觉得它实现得很糟糕,这是我的问题 - 是否有更好的方法来实现异步api?

0 个答案:

没有答案