Home > Software engineering >  Correct way to use async await with AcquireTokenForClient().ExecuteAsync
Correct way to use async await with AcquireTokenForClient().ExecuteAsync

Time:07-26

I am new to the async await method in C#. I have a function called InitServiceAsync I am new to the async await method in C# which will init the service and get the tokens for this client because AcquireTokenForClient(s).ExecuteAsync() is an async funtion so I use await to wait for authentication data

Then I assign the task.Result return from InitServiceAsync() to _service Will it cause dead lock? Can anyone suggest what is the right way to call AcquireTokenForClient with async/await correctly? Thanks

void fun(){
    Task<ExchangeService> task = InitServiceAsync();
    _service = task.Result;
}
private static async Task<ExchangeService> InitServiceAsync()
       {
           ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1, tzi);
           var cca = ConfidentialClientApplicationBuilder
                   .Create(appId)
                   .WithClientSecret(clientSecret)
                   .WithTenantId(tenantId)
                   .Build();
           var s = new string[] { "https://outlook.office365.com/.default" };
           var authResult = await cca.AcquireTokenForClient(s).ExecuteAsync().ConfigureAwait(false);
           service.Credentials = new OAuthCredentials(authResult.AccessToken);
           return service;
       }

CodePudding user response:

if you use "task.Result" you will wait for the execution of the async task which will make it more or less synchron again.

ExchangeService exchangeService = await InitServiceAsync(); _service = exchangeService;

I m also no total expert, there are plenty other devs which will explain it to you better, but thats the way i would handle it :)

"The only difference is that the await will not block. Instead, it will asynchronously wait for the Task to complete and then resume" see here Await vs Task.Result in an Async Method

CodePudding user response:

With the introduction of Asynchronous Main, I don't think much is left to call an asynchronous Method in a synchronous context.

I would suggest you do,

async Task fun()
{
    _service =await InitServiceAsync();
}

If this code is part of a constructor, then, I would suggest you initialize it first and then inject the initialized version in constructor.

At last, if you are building a library, and want to provide synchronous version of async code, then you can refer to these answers. Suggest you go through at least 3-4 answers before making your decision. How to call asynchronous method in sync

  • Related