r mk r r mk r - 3 months ago 9
C# Question

Asynchronous module completed while another operation is pending

I am connecting to the Quickbooks api, download the employees inforamtion and saving it to my local database. I am using angularjs, webapi to accomplish this. I am getting the following error when I am saving the info to database. I do see all the functions have async and await. Can some body please help me why I am getting this error.

Error :


Server Error in '/' Application.An asynchronous module or handler completed while an asynchronous operation was still pending.


Problem is happening in the below pasted piece of code:

var candidate = await CandidateLoginBL.AddCandidateByEmployeeAsync(new CandidateLoginBO()
{
FirstName = e.GivenName,
MiddleName = e.MiddleName,
LastName = e.FamilyName
});
}
});


The full flow is as follows :

js :

QuickbookModule.factory('QuickbookService', ['$http', function ($http) {

return {
getQuickbooksSync: function () {
return $http({
url: '/api/QuickbookService/syncQuickbooks',
method: 'GET',
params: { IdCompany: sessionStorage.CID }
});
}


API Controller :

[HttpGet]
[Route("syncQuickbooks")]
public async Task<IHttpActionResult> syncQuickbooks(int IdCompany)
{
var result = await QuickbooksBL.FullQuickbooksSync(IdCompany);
return Ok(result);
}


QuickbooksBL :

public static async Task<List<IncompleteEmp>> FullQuickbooksSync(int IdCompany)
{return await SyncronizeEmps(IdCompany); }

public static async Task<List<IncompleteEmp>> SyncronizeEmps(int companyId)
{
......
List<EmployeeBO> empList = new List<EmployeeBO>();
await AddToHumanEfits(companyId, inQBEmpsInfo); ....
}
return IncompleteEmps;
}


public static async Task AddToHumanEfits(int companyId, List<EmployeeQbOnlineBO> qbEmpsList)
{
....
qbEmpsList.ForEach(async e =>
{

// Add a record into Candidate Login.

var candidate = await CandidateLoginBL.AddCandidateByEmployeeAsync(new CandidateLoginBO()
{
FirstName = e.GivenName,
MiddleName = e.MiddleName,
LastName = e.FamilyName });
}
});
}


CandidateContactBL :

public static async Task<CandidateLoginBO> AddCandidateByEmployeeAsync(CandidateLoginBO model)
{
return await CandidateLoginDAL.AddCandidateByEmployeeAsync(model);
}


CandidateContactDAL :

public static async Task<CandidateLoginBO> AddCandidateByEmployeeAsync(CandidateLoginBO model)
{
CandidateLoginBO candidate = new CandidateLoginBO();

candidate = await GetByUserNameAsync(new CandidateLoginBO() { Email = model.Email }); candidate = await AddEmployeeAsync(model);
return candidate;
}

Answer

This kind of error is commonly caused by async void. And I see one right here:

qbEmpsList.ForEach(async e =>
{
  ...
});

You'd probably want to make this into a regular foreach:

foreach (var e in qbEmpsList)
{
  ...
}