Skip to content

Commit

Permalink
Adds more cancellation token usage
Browse files Browse the repository at this point in the history
Add consistancy to cancellationToken naming convention
Few typos fixed up
  • Loading branch information
DaveHogan authored and phongnguyend committed Sep 4, 2024
1 parent 08052db commit 7efd626
Show file tree
Hide file tree
Showing 37 changed files with 95 additions and 95 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@ public AddEntityCommandHandler(ICrudService<TEntity> crudService)

public async Task HandleAsync(AddEntityCommand<TEntity> command, CancellationToken cancellationToken = default)
{
await _crudService.AddAsync(command.Entity);
await _crudService.AddAsync(command.Entity, cancellationToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@ public AddOrUpdateEntityCommandHandler(ICrudService<TEntity> crudService)

public async Task HandleAsync(AddOrUpdateEntityCommand<TEntity> command, CancellationToken cancellationToken = default)
{
await _crudService.AddOrUpdateAsync(command.Entity);
await _crudService.AddOrUpdateAsync(command.Entity, cancellationToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ public DeleteEntityCommandHandler(ICrudService<TEntity> crudService)

public async Task HandleAsync(DeleteEntityCommand<TEntity> command, CancellationToken cancellationToken = default)
{
await _crudService.DeleteAsync(command.Entity);
await _crudService.DeleteAsync(command.Entity, cancellationToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@ public UpdateEntityCommandHandler(ICrudService<TEntity> crudService)

public async Task HandleAsync(UpdateEntityCommand<TEntity> command, CancellationToken cancellationToken = default)
{
await _crudService.UpdateAsync(command.Entity);
await _crudService.UpdateAsync(command.Entity, cancellationToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context
{
try
{
var response = await _httpClient.GetAsync(_uri);
var response = await _httpClient.GetAsync(_uri, cancellationToken);
if (response.IsSuccessStatusCode)
{
return HealthCheckResult.Healthy($"Uri: '{_uri}', StatusCode: '{response.StatusCode}'");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,23 @@ public abstract class CronJobBackgroundService : BackgroundService
{
protected string Cron { get; set; }

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
var cron = new CronExpression(Cron);
var next = cron.GetNextValidTimeAfter(DateTimeOffset.Now);

while (!stoppingToken.IsCancellationRequested)
while (!cancellationToken.IsCancellationRequested)
{
if (DateTimeOffset.Now > next)
{
await DoWork(stoppingToken);
await DoWork(cancellationToken);

next = cron.GetNextValidTimeAfter(DateTimeOffset.Now);
}

await Task.Delay(1000, stoppingToken);
await Task.Delay(1000, cancellationToken);
}
}

protected abstract Task DoWork(CancellationToken stoppingToken);
protected abstract Task DoWork(CancellationToken cancellationToken);
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ public MessageBusConsumerBackgroundService(ILogger<MessageBusConsumerBackgroundS
_messageBus = messageBus;
}

protected override Task ExecuteAsync(CancellationToken stoppingToken)
protected override Task ExecuteAsync(CancellationToken cancellationToken)
{
_messageBus.ReceiveAsync<TConsumer, T>(stoppingToken);
_messageBus.ReceiveAsync<TConsumer, T>(cancellationToken);
return Task.CompletedTask;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context
try
{
var client = new ServiceBusAdministrationClient(_connectionString);
var queue = await client.GetQueueAsync(_queueName);
var queue = await client.GetQueueAsync(_queueName, cancellationToken);

if (string.Equals(queue?.Value?.Name, _queueName, StringComparison.OrdinalIgnoreCase))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ public Task ReceiveAsync(Func<T, MetaData, Task> action, CancellationToken cance
catch (Exception ex)
{
// TODO: log here
await Task.Delay(1000);
await Task.Delay(1000, cancellationToken);
_channel.BasicNack(deliveryTag: ea.DeliveryTag, multiple: false, requeue: _options.RequeueOnFailure);
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public async Task<List<AuditLogEntryDTO>> HandleAsync(GetAuditEntriesQuery query
query = query.AsNoTracking();
}

var auditLogs = await query.ToListAsync();
var auditLogs = await query.ToListAsync(cancellationToken: cancellationToken);
var users = await _dispatcher.DispatchAsync(new GetUsersQuery(), cancellationToken);

var rs = auditLogs.Join(users, x => x.UserId, y => y.Id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,12 @@ public async Task<Paged<AuditLogEntryDTO>> HandleAsync(GetPagedAuditEntriesQuery

var result = new Paged<AuditLogEntryDTO>
{
TotalItems = await query.CountAsync(),
TotalItems = await query.CountAsync(cancellationToken: cancellationToken),
};

var auditLogs = await query.OrderByDescending(x => x.CreatedDateTime)
.Paged(queryOptions.Page, queryOptions.PageSize)
.ToListAsync();
.ToListAsync(cancellationToken: cancellationToken);

var users = await _dispatcher.DispatchAsync(new GetUsersQuery(), cancellationToken);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public AddUpdateRoleCommandHandler(IRoleRepository roleRepository)

public async Task HandleAsync(AddUpdateRoleCommand command, CancellationToken cancellationToken = default)
{
await _roleRepository.AddOrUpdateAsync(command.Role);
await _roleRepository.AddOrUpdateAsync(command.Role, cancellationToken);
await _roleRepository.UnitOfWork.SaveChangesAsync(cancellationToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public AddClaimCommandHandler(IUserRepository userRepository)
public async Task HandleAsync(AddClaimCommand command, CancellationToken cancellationToken = default)
{
command.User.Claims.Add(command.Claim);
await _userRepository.AddOrUpdateAsync(command.User);
await _userRepository.AddOrUpdateAsync(command.User, cancellationToken);
await _userRepository.UnitOfWork.SaveChangesAsync(cancellationToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public AddRoleCommandHandler(IUserRepository userRepository)
public async Task HandleAsync(AddRoleCommand command, CancellationToken cancellationToken = default)
{
command.User.UserRoles.Add(command.Role);
await _userRepository.AddOrUpdateAsync(command.User);
await _userRepository.AddOrUpdateAsync(command.User, cancellationToken);
await _userRepository.UnitOfWork.SaveChangesAsync(cancellationToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public DeleteClaimCommandHandler(IUserRepository userRepository)
public async Task HandleAsync(DeleteClaimCommand command, CancellationToken cancellationToken = default)
{
command.User.Claims.Remove(command.Claim);
await _userRepository.AddOrUpdateAsync(command.User);
await _userRepository.AddOrUpdateAsync(command.User, cancellationToken);
await _userRepository.UnitOfWork.SaveChangesAsync(cancellationToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public DeleteRoleCommandHandler(IUserRepository userRepository)
public async Task HandleAsync(DeleteRoleCommand command, CancellationToken cancellationToken = default)
{
command.User.UserRoles.Remove(command.Role);
await _userRepository.AddOrUpdateAsync(command.User);
await _userRepository.AddOrUpdateAsync(command.User, cancellationToken);
await _userRepository.UnitOfWork.SaveChangesAsync(cancellationToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ public SyncUsersWorker(IServiceProvider services,
_logger = logger;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
_logger.LogDebug("SyncUsersWorker is starting.");

while (!stoppingToken.IsCancellationRequested)
while (!cancellationToken.IsCancellationRequested)
{
_logger.LogDebug($"SyncUsersWorker doing background work.");

Expand All @@ -35,12 +35,12 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var dispatcher = scope.ServiceProvider.GetRequiredService<Dispatcher>();

await dispatcher.DispatchAsync(syncUsersCommand, stoppingToken);
await dispatcher.DispatchAsync(syncUsersCommand, cancellationToken);
}

if (syncUsersCommand.SyncedUsersCount == 0)
{
await Task.Delay(10000, stoppingToken);
await Task.Delay(10000, cancellationToken);
}
}

Expand Down
18 changes: 9 additions & 9 deletions src/ModularMonolith/ClassifiedAds.Modules.Identity/UserStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ public void Dispose()

public async Task<IdentityResult> CreateAsync(User user, CancellationToken cancellationToken)
{
await _userRepository.AddOrUpdateAsync(user);
await _unitOfWork.SaveChangesAsync();
await _userRepository.AddOrUpdateAsync(user, cancellationToken);
await _unitOfWork.SaveChangesAsync(cancellationToken);
return IdentityResult.Success;
}

Expand All @@ -51,17 +51,17 @@ public Task<IdentityResult> DeleteAsync(User user, CancellationToken cancellatio

public Task<User> FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken)
{
return _userRepository.Get(new UserQueryOptions { IncludeTokens = true }).FirstOrDefaultAsync(x => x.NormalizedEmail == normalizedEmail);
return _userRepository.Get(new UserQueryOptions { IncludeTokens = true }).FirstOrDefaultAsync(x => x.NormalizedEmail == normalizedEmail, cancellationToken: cancellationToken);
}

public Task<User> FindByIdAsync(string userId, CancellationToken cancellationToken)
{
return _userRepository.Get(new UserQueryOptions { IncludeTokens = true }).FirstOrDefaultAsync(x => x.Id == Guid.Parse(userId));
return _userRepository.Get(new UserQueryOptions { IncludeTokens = true }).FirstOrDefaultAsync(x => x.Id == Guid.Parse(userId), cancellationToken: cancellationToken);
}

public Task<User> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken)
{
return _userRepository.Get(new UserQueryOptions { IncludeTokens = true }).FirstOrDefaultAsync(x => x.NormalizedUserName == normalizedUserName);
return _userRepository.Get(new UserQueryOptions { IncludeTokens = true }).FirstOrDefaultAsync(x => x.NormalizedUserName == normalizedUserName, cancellationToken: cancellationToken);
}

public Task<int> GetAccessFailedCountAsync(User user, CancellationToken cancellationToken)
Expand Down Expand Up @@ -225,8 +225,8 @@ public Task SetUserNameAsync(User user, string userName, CancellationToken cance

public async Task<IdentityResult> UpdateAsync(User user, CancellationToken cancellationToken)
{
await _userRepository.AddOrUpdateAsync(user);
await _unitOfWork.SaveChangesAsync();
await _userRepository.AddOrUpdateAsync(user, cancellationToken);
await _unitOfWork.SaveChangesAsync(cancellationToken);
return IdentityResult.Success;
}

Expand Down Expand Up @@ -260,7 +260,7 @@ public async Task SetTokenAsync(User user, string loginProvider, string name, st
});
}

await _unitOfWork.SaveChangesAsync();
await _unitOfWork.SaveChangesAsync(cancellationToken);
}

public async Task RemoveTokenAsync(User user, string loginProvider, string name, CancellationToken cancellationToken)
Expand All @@ -270,7 +270,7 @@ public async Task RemoveTokenAsync(User user, string loginProvider, string name,
if (tokenEntity != null)
{
user.Tokens.Remove(tokenEntity);
await _unitOfWork.SaveChangesAsync();
await _unitOfWork.SaveChangesAsync(cancellationToken);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ await _emailNotification.SendAsync(new DTOs.EmailMessageDTO
BCCs = email.BCCs,
Subject = email.Subject,
Body = email.Body,
});
}, cancellationToken);

email.SentDateTime = _dateTimeProvider.OffsetNow;
email.Log += log + "Succeed.";
Expand All @@ -96,7 +96,7 @@ await _emailNotification.SendAsync(new DTOs.EmailMessageDTO
email.MaxAttemptCount = defaultAttemptCount;
}

await _repository.UnitOfWork.SaveChangesAsync();
await _repository.UnitOfWork.SaveChangesAsync(cancellationToken);
}
}
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ await _smsNotification.SendAsync(new DTOs.SmsMessageDTO
{
Message = sms.Message,
PhoneNumber = sms.PhoneNumber,
});
}, cancellationToken);

sms.SentDateTime = _dateTimeProvider.OffsetNow;
sms.Log += log + "Succeed.";
Expand All @@ -92,7 +92,7 @@ await _smsNotification.SendAsync(new DTOs.SmsMessageDTO
sms.MaxAttemptCount = defaultAttemptCount;
}

await _repository.UnitOfWork.SaveChangesAsync();
await _repository.UnitOfWork.SaveChangesAsync(cancellationToken);
}
}
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,27 @@

namespace ClassifiedAds.Modules.Notification.HostedServices;

public class SendEmailWoker : BackgroundService
public class SendEmailWorker : BackgroundService
{
private readonly IServiceProvider _services;
private readonly ILogger<SendEmailWoker> _logger;
private readonly ILogger<SendEmailWorker> _logger;

public SendEmailWoker(IServiceProvider services,
ILogger<SendEmailWoker> logger)
public SendEmailWorker(IServiceProvider services,
ILogger<SendEmailWorker> logger)
{
_services = services;
_logger = logger;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
_logger.LogDebug("SendEmailService is starting.");
await DoWork(stoppingToken);
await DoWork(cancellationToken);
}

private async Task DoWork(CancellationToken stoppingToken)
private async Task DoWork(CancellationToken cancellationToken)
{
while (!stoppingToken.IsCancellationRequested)
while (!cancellationToken.IsCancellationRequested)
{
_logger.LogDebug($"SendEmail task doing background work.");

Expand All @@ -39,12 +39,12 @@ private async Task DoWork(CancellationToken stoppingToken)
{
var dispatcher = scope.ServiceProvider.GetRequiredService<Dispatcher>();

await dispatcher.DispatchAsync(sendEmailsCommand);
await dispatcher.DispatchAsync(sendEmailsCommand, cancellationToken);
}

if (sendEmailsCommand.SentMessagesCount == 0)
{
await Task.Delay(10000, stoppingToken);
await Task.Delay(10000, cancellationToken);
}
}

Expand Down
Loading

0 comments on commit 7efd626

Please sign in to comment.