等待从函数返回后无法访问的代码

时间:2019-03-26 13:58:50

标签: c# async-await return-value

我想从函数中等待返回

我已经尝试使用GetAwaiter()。GetResult() 我也尝试过从函数较高和较低的不可达代码移动返回。在较低的情况下,我只是在所有计算后得到结果。如果代码较高,则将较低的代码标记为无法访问且不起作用。

 public async Task<Guid?> Start(IServiceProvider serviceProvider, FileDTO[] files, Guid? guidOfCurrentService)
    {
        var serviceRepository = serviceProvider.GetService<IServiceRepository>();
        if (!serviceRepository.CheckService(guidOfCurrentService))
        {
            if (guidOfCurrentService == null)
            {
                guidOfCurrentService = Guid.NewGuid();
            }
            var service = serviceProvider.GetService<ICompressingService>();
            serviceRepository.StartService(guidOfCurrentService);
            _serviceResolver.Add(guidOfCurrentService, service);
            return _serviceResolver.FirstOrDefault(x => x.Value == service).Key;
            try
            {
                await Task.Run(() => service.CompressFiles(files));
            }
            catch
            {
                serviceRepository.EndService(guidOfCurrentService);
                return null;
            }
            serviceRepository.EndService(guidOfCurrentService);
        }
        else
        {
            return null;
        }
    }

我如何从此函数中获得等待的回报: _serviceResolver.FirstOrDefault(x => x.Value == service).Key; 并继续尝试/捕获等功能?谢谢

1 个答案:

答案 0 :(得分:1)

return始终表示函数的结尾。我建议存储对_serviceResolver...的调用结果,并在try-catch-block之后将其返回,如下所示:

var _result = _serviceResolver.FirstOrDefault(x => x.Value == service).Key;
try
{
    await Task.Run(() => service.CompressFiles(files));
}
catch
{
    serviceRepository.EndService(guidOfCurrentService);
    return null;
}
serviceRepository.EndService(guidOfCurrentService);
return _result;