We have a WCF service with methods and their asyncs, we want to call them async.
The following code hangs up:
private void btnRunTest_Click(object sender, EventArgs e)
{
Task<List<DtoEmployee>> resultOfLoadEmployees = LoadEmployeesAsync(predicateEmployee1); // hangs up on this line
resultOfLoadEmployees.Wait();
var employeeList = resultOfLoadEmployees.Result;
foreach (var item in employeeList)
{
//Do Something
}
}
private async Task<List<DtoEmployee>> LoadEmployeesAsync(int employeeNumber)
{
return await _serviceClient.EmployeeGetListAsync(employeeNumber);
}
but the following code is OK and runs without a problem:
private async Task<List<DtoEmployee>> LoadEmployeesAsync(int employeeNumber)
{
return await _serviceClient.EmployeeGetListAsync(employeeNumber);
}
private async void btnRunTest_Click(object sender, EventArgs e)
{
List<DtoEmployee> employeeList = await LoadEmployeesAsync(employeeNumber);
foreach (var item in employeeList)
{
//Do Something
}
}
What's the differences and which one is correct to call async WCF method?
That difference is that the former deadlocks here:
A synchronization context is trying to marshal the continuation work back (everything after your first
await
) but can't because it's blocked via aWait()
call, which synchronously blocks. The latter properly asynchronously waits on the result to return, while not blocking the call. That's why you shouldn't block no async codeYou should use the latter.
Side note - you can save yourself the state-machine generation as you can simply return the hot task created by
EmployeeGetListAsync
: