Await kills process

后端 未结 2 1879
一生所求
一生所求 2021-01-19 07:46

I am trying to connect to Azure AD and I am using this code.

try
{
    var clientCredential = new ClientCredential(_clientId, _clientSecret);
    var authCon         


        
相关标签:
2条回答
  • 2021-01-19 08:22

    the process is simply killed. No exception is thrown, nothing.

    I assume that you are running this in a Console application, and that your top-level code would look something like this:

    static void Main()
    {
      MyMethodAsync();
    }
    

    In which case, the main method would in fact exit, since it is not waiting for your asynchronous code to complete.

    One way to work with async in Console applications is to block in the Main method. Normally, you want to go "async all the way", but a Console app's Main method is an exception to this rule:

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

    Update: Don't use async void; use async Task instead:

    static async Task ImportLicenceAsync()
    {
      await InsertToDbAsync();
    }
    
    public async Task InsertoDbAsync()
    {
      var x = await GetSPAsync();
    }
    
    0 讨论(0)
  • 2021-01-19 08:47

    Update code so that it is async all the way through. Make sure that you are not mixing async and sync code higher up the call stack. Avoid using 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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题