제목과 정확히 같습니다. 나는 비동기를 작성하고 그것이 필요하지 않을 때를 기다리는 지 궁금해.async 및 C#에 필요한 대기 시간은 언제입니까?
나는 둘 다 잘 컴파일이
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();
}
없이 비동기 태그
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();
}
이 같은이 같은 방법을 보았다. 나는 항상 비동기를 추가하고 키워드를 기다리고 어쩌면 내가 잘못하고 있고 필요하지 않을 때 쓰는 지 궁금해 할까?
는편집 :
실제로 값을 반환하는 경우, 이것은 비동기를 사용하여 작성해야/키워드 또는하지를 기다리고 있습니다. 다음은 키워드 여기
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;
}
있는 버전은 또 다른 예
public Task<User> FindByIdAsync(long userId)
{
return _context.Users.FindAsync(userId);
}
public async Task<User> FindByIdAsync(long userId)
{
return await _context.Users.FindAsync(userId);
}
편집 지금까지 2
우수 답변 만 1 마지막 예이다. 이후 내 비동기 호출을 가지고, 어떻게 하나의 방법에서 여러 비동기 함수를 호출 대처합니다. 여기에 내가 가진 것에 대한 예가 있지만 그것이 옳은지 나는 모른다. 모든 AddAsync 메서드가 완료 될 때까지 메서드를 종료하지 않으려합니다. 가이 올바른 경우에만이 방법을 반환하거나 비동기 작업의 결과로 뭔가를 필요로 할 때 SaveChangesAsync
작업을 완료 할 경우 await
를 사용할 필요가 이럴
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"));
}
[비동기 및 기다리고 있습니다]의 중복 가능성 (http://stackoverflow.com/questions/14455293/async-and-await) –