Async task method returns right after one of it await tasks executed without proceeding to next task
My project is MVC.net 4.7.2. A Controller action method calls a chain of methods. One of the methods is calling the Microsoft Graph API built-in async method. When the method executes, it returns quickly with the process of rest of the code.
Below is the code when "result = await app.AcquireTokenForClient(scopes)" executes and return.
public string AddRequest(List<names> collections)
{ //removed some code here
email.SendEmailSimpleEmail();
}
public async Task SendEmailSimpleEmail()
{
//var token = await GetGraphAccessToken();
// With client credentials flows
var app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
//.WithTenantId(tenant)
.WithAuthority(authority)
.Build();
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
AuthenticationResult result = null;
try
{
result = await
app.AcquireTokenForClient(scopes).
ExecuteAsync();
var graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", result.AccessToken);
}));
//removed the rest of the code and also the try and catch block too
}
Solution 1:
All awaitables need to be awaited.
In an asynchronous method, the code runs synchronously until the first await
of a non-completed awaitable.
That's what happens when the execution reaches the invocation of app.AcquireTokenForClient(scopes).ExecuteAsync()
.
Because that awaitable hasn't completed, the execution of that method is interrupted and the control is returned to the invoking method.
Because the invoking method (AddRequest
) is not awaiting the Task
returned by SendEmailSimpleEmail
, the execution continues, and the execution exits AddRequest
.