简体   繁体   中英

WCF async method calling hangs up?

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?

What's the differences and which one is correct to call async WCF method?

That difference is that the former deadlocks here:

resultOfLoadEmployees.Wait();

A synchronization context is trying to marshal the continuation work back (everything after your first await ) but can't because it's blocked via a Wait() 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 code

You 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 :

private Task<List<DtoEmployee>> LoadEmployeesAsync(int employeeNumber)
{
    return _serviceClient.EmployeeGetListAsync(employeeNumber);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM