i use async funcs with await Task.WhenAll inmy function. and some times i get exception with this message "A second operation was started on this context before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext".
public async Task<int> getCountAsync(long userId)
{
return await _appDbContenxt.onTimeRequests
.Where(i => (userId == 0 ? true : i.userId == userId))
.CountAsync()
;
}
public async Task<List<OnTimeRequest>> GetOnTimeRequestsAsync(int pageSize, int currentPage, long userId)
{
return await _appDbContenxt.onTimeRequests
.Where(i => (userId == 0 ? true : i.userId == userId))
.OrderByDescending(i => i.id)
.Skip((currentPage - 1) * pageSize)
.Take(pageSize)
.ToListAsync()
;
}
public async Task<OnTimePaginationDto> getUserOnTimeRequests(int pageSize, int currentPage, long userId)
{
Task<int> count = _onTimeRequestsRepository.getCountAsync(userId);
Task<List<OnTimeRequest>> values = _onTimeRequestsRepository.GetOnTimeRequestsAsync(pageSize, currentPage, userId);
await Task.WhenAll(count, values);
OnTimePaginationDto onTimePaginationDto = new OnTimePaginationDto
{
count = count.Result,
values = _mapper.Map<IList<ReadOnTimeRequestDto>>(values.Result)
};
return onTimePaginationDto;
}
this is my functions. getUserOnTimeRequests in on timeRequestService. getCountAsync and GetOnTimeRequestsAsync in timeRequestRepository . and this is my startup code
services.AddScoped<IMemberSheetRepository, MemberShiptRepository>();
services.AddScoped<IPackageHistoryRepository, PackageHistoryRepository>();
services.AddScoped<IOnTimeRequestsRepository, OnTimeRequestsRepository>();
services.AddScoped<IMemberShipService, MemberShipService>();
services.AddScoped<IPackageHistoryService, PackageHistoryService>();
services.AddScoped<IOnTimeRequestService, OnTimeRequestService>();
services.AddDbContext<AppDbContext>(options =>
options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
.UseSqlServer(Configuration.GetConnectionString("DbConnection")),ServiceLifetime.Transient
);
thanks for your helps.