等待杀死进程

时间:2017-02-01 15:06:45

标签: c# asynchronous async-await azure-active-directory microsoft-graph

我正在尝试连接到Azure AD并且我正在使用此代码。

try
{
    var clientCredential = new ClientCredential(_clientId, _clientSecret);
    var authContext = new AuthenticationContext(AuthUri + _tenant);
    var authResult = await authContext.AcquireTokenAsync(GraphUri,clientCredential);
    var authString = authResult.CreateAuthorizationHeader();
    var client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var request = new HttpRequestMessage
    {
        Method = HttpMethod.Get,
        RequestUri = _requestUri,
    };
    request.Headers.Add("Authorization", authString);
    HttpResponseMessage response = null;
    await client.SendAsync(request).ContinueWith(taskWithMessage =>
    {
        response = taskWithMessage.Result;
    });
    return await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
   Console.WriteLine(ex);
}

我不明白的一个大问题是,当执行到达第一个等待(var authResult = await authContext.AcquireTokenAsync(GraphUri,clientCredential);)时,该过程就会被杀死。没有异常被抛出,没有。

如果我用

替换该行
var authResult = authContext.AcquireTokenAsync(GraphUri,clientCredential); 
var authString = authResult.Result.CreateAuthorizationHeader();

执行一直持续到await client.SendAsync(request).ContinueWith(taskWithMessage...,其中进程再次被杀死,没有抛出任何异常或任何警告或其他消息。

更奇怪的是,这个代码在另一个项目中运行得很好,但在这里它不会工作。

编辑:

static void ImportLicence()
{
   InsertToDb();
}

public async void InsertoDb()
{
   var x = await GetSP();
}

public async Task<Dictionary<ServicePlanViewModel, List<ServicePlanViewModel>>> GetSP()
{
   var sp = await MakeRq();
}

public async Task<string> MakeRequest()
{
   var authString = await GetAuth();
   ..........
   return await response.Content.ReadAsStringAsync();
}

private async Task<string> GetAuth()
{
   .....
   var authResult = await authContext.AcquireTokenAsync(GraphUri, clientCredential);
   return authResult.CreateAuthorizationHeader();
}

2 个答案:

答案 0 :(得分:6)

  

这个过程被简单地杀死了。没有异常被抛出,没有。

我假设你在控制台应用程序中运行它,并且你的顶级代码看起来像这样:

static void Main()
{
  MyMethodAsync();
}

在这种情况下,main方法实际上会退出,因为它不等待您的异步代码完成。

在控制台应用程序中使用async的一种方法是在Main方法中阻止。通常,您希望一直“异步”#34;但是控制台应用的Main方法是此规则的例外情况:

static void Main() => MainAsync().GetAwaiter().GetResult();
static async Task MainAsync()
{
  // Original code from Main, but adding any necessary `await`s.
  await MyMethodAsync();
}

更新: Don't use async void;改为使用async Task

static async Task ImportLicenceAsync()
{
  await InsertToDbAsync();
}

public async Task InsertoDbAsync()
{
  var x = await GetSPAsync();
}

答案 1 :(得分:1)

更新代码,使其始终处于异步状态。确保您没有在调用堆栈的上方混合异步和同步代码。避免使用async void

public async Task<string> SomeMethodAsync() {
    try {
        var clientCredential = new ClientCredential(_clientId, _clientSecret);
        var authContext = new AuthenticationContext(AuthUri + _tenant);
        var authResult = await authContext.AcquireTokenAsync(GraphUri,clientCredential);
        var authString = authResult.CreateAuthorizationHeader();
        var client = new HttpClient();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var request = new HttpRequestMessage {
            Method = HttpMethod.Get,
            RequestUri = _requestUri,
        };
        request.Headers.Add("Authorization", authString);

        using(var response = await client.SendAsync(request)) {
            return await response.Content.ReadAsStringAsync();
        }    
    } catch (Exception ex) {
       Console.WriteLine(ex);
    }
}