Остановить выполнение функции при успешном выполнении HTTP-запроса ASP.NET Ядро

#asp.net-core

#asp.net-core

Вопрос:

Мое требование заключается в том, что если запрос выполнен успешно, то он не может быть выполнен снова. Но теперь он вызывается каждый раз:

 public async Task Send(CancellationToken token)
{
    logger.LogInformation("E-mail background delivery started");

    while (!token.IsCancellationRequested)
    {

        try
        {
            if (FullUrl != null)
            {
                var request = new HttpRequestMessage(HttpMethod.Get, FullUrl);

                // Let's wait for a message to appear in the queue
                // If the token gets canceled, then we'll stop waiting
                // since an OperationCanceledException will be thrown

                var client = _clientFactory.CreateClient();

                // token.ThrowIfCancellationRequested();

                var response = await client.SendAsync(request, token).ConfigureAwait(false);

                if (!response.IsSuccessStatusCode)
                {
                    logger.LogInformation($"E-mail sent to");
                }
            }


            //as soon as a message is available, we'll send it
            logger.LogInformation($"E-mail sent to");
        }
        catch (OperationCanceledException)
        {
            //We need to terminate the delivery, so we'll just break the while loop
            break;
        }
        catch(Exception e)
        {
            #warning Implement a retry mechanism or else this message will be lost
            logger.LogWarning($"Couldn't send an e-mail to");
            break;
        }
    }

    logger.LogInformation("E-mail background delivery stopped");
}
  

Комментарии:

1. Я думаю, что неясно, о чем вы просите, не могли бы вы, пожалуйста, прояснить свой вопрос.

2. итак, вы хотите выйти из while цикла, если запрос был успешным? почему бы просто не изменить флаг вашего цикла на while (!requestSuccessful) { if (!token.IsCancellationRequested { // ... } } и не установить requestSuccessful значение true if response.IsSuccessStatuscode ?

Ответ №1:

Попробуйте в приведенном ниже коде добавить переменную, чтобы указать, является ли reposne успешным.

 public async Task Send(CancellationToken token)
{
    logger.LogInformation("E-mail background delivery started");
    bool IsSuccess = false;
    while (!token.IsCancellationRequested amp;amp; !IsSuccess)
    {

        try
        {
            if (FullUrl != null)
            {
                var request = new HttpRequestMessage(HttpMethod.Get, FullUrl);

                // Let's wait for a message to appear in the queue
                // If the token gets canceled, then we'll stop waiting
                // since an OperationCanceledException will be thrown

                var client = _clientFactory.CreateClient();

                // token.ThrowIfCancellationRequested();

                var response = await client.SendAsync(request, token).ConfigureAwait(false);

                if (!response.IsSuccessStatusCode)
                {
                    logger.LogInformation($"E-mail sent to");
                }
                else
                {
                    IsSuccess = true;
                }
            }


            //as soon as a message is available, we'll send it
            logger.LogInformation($"E-mail sent to");
        }
        catch (OperationCanceledException)
        {
            //We need to terminate the delivery, so we'll just break the while loop
            break;
        }
        catch(Exception e)
        {
            #warning Implement a retry mechanism or else this message will be lost
            logger.LogWarning($"Couldn't send an e-mail to");
            break;
        }
    }

    logger.LogInformation("E-mail background delivery stopped");
}