等待调用Web服务正在停止程序的执行流程

时间:2016-09-12 11:33:25

标签: async-await c#-5.0

我有以下代码:

public async Task IntiateDataFetchingProcess(string[] args)
{
    try
    {           
        ProcessArgs(args);

        Log.Information("Run Mode: {RunModeID}", RunModeID);

        switch (RunModeID)
        {
            case RunModeType.A:
                await MethodAAsync();
                break;
            case RunModeType.B:
                await MethodBAsync();
                break;
            case RunModeType.C:
                TestMethod();
                break;
            default:                       
                break;
        }
    }
    catch (Exception ex)
    {                
        throw;
    }            
}

private async Task MethodBAsync()
{
   Console.WriteLine(DateTime.Now.ToLongTimeString());

   // Call to webservice to get the data
   var response = await _service.GetDataAsync(input1, request);

   Console.WriteLine(DateTime.Now.ToLongTimeString());  
}

在调试时,我发现执行调用来自下面一行(方法:MethodBAsync)并停在那里。

var response = await _service.GetDataAsync(input1, request);

任何人都可以帮助我知道我在这里缺少什么。

1 个答案:

答案 0 :(得分:1)

啊,你的代码陷入僵局! 您只需将.ConfigureAwait(false);添加到await

的每一行

示例:

var response = await _service.GetDataAsync(input1, request);

变为

var response = await _service.GetDataAsync(input1, request).ConfigureAwait(false);

有关.ConfigureAwait()的更多信息,Stephen Cleary写了an awesome post on it