Exactly as the title says. I wonder if i am writing async and await when it is not needed.
I have seen methods like this with the async tag
public async Task CreateAsync(User user)
{
if (_context.Entry<User>(user).State == EntityState.Detached)
{
_context.Set<User>().Add(user);
}
_context.Entry<User>(user).State = EntityState.Added;
await _context.SaveChangesAsync();
}
and like this without it
public Task CreateAsync(User user)
{
if (_context.Entry<User>(user).State == EntityState.Detached)
{
_context.Set<User>().Add(user);
}
_context.Entry<User>(user).State = EntityState.Added;
return _context.SaveChangesAsync();
}
Both compile fine. I am always adding the async and await keywords and wonder maybe if i am doing it wrong and writing them when they are not needed?
EDIT:
If you are actually returning a value, should this be written using the async/await keywords, or without. Here is a version with the keywords
public async Task<User> CreateAsync(User user)
{
if (_context.Entry<User>(user).State == EntityState.Detached)
{
_context.Set<User>().Add(user);
}
_context.Entry<User>(user).State = EntityState.Added;
await _context.SaveChangesAsync();
return user;
}
here is another example
public Task<User> FindByIdAsync(long userId)
{
return _context.Users.FindAsync(userId);
}
public async Task<User> FindByIdAsync(long userId)
{
return await _context.Users.FindAsync(userId);
}
EDIT 2
Excellent answers so far, but 1 last example. Since i have my async calls, how would i cope with calling multiple async functions from 1 method. here is an example of what i have, but i dont know if it is right. I do not want the method to exit until all AddAsync methods are completed. Is this correct
private async Task AddPermissions(DataContext context)
{
var permissionService = new PermissionService(context);
await permissionService.AddAsync(new Permission("CanView", "View company"));
await permissionService.AddAsync(new Permission("CanAdd", "Add and view company"));
await permissionService.AddAsync(new Permission("CanEdit", "Edit and view company"));
await permissionService.AddAsync(new Permission("CanDelete", "Delete and view company record"));
await permissionService.AddAsync(new Permission("CanAdd", "Add new pages"));
await permissionService.AddAsync(new Permission("CanEdite", "Edit existing pages"));
await permissionService.AddAsync(new Permission("CanDelete", "Delete a page"));
await permissionService.AddAsync(new Permission("CanAdd", "Add new page content"));
await permissionService.AddAsync(new Permission("CanEdit", "Edit existing page content"));
await permissionService.AddAsync(new Permission("CanDelete", "Delete page content"));
}