Not understandable behavior when waitingAsync SemaphoreSlim

18 views Asked by At

I am trying sending email using this code

for (int i = 1; i <= 10; i++)
            {
                var sendResponse = emailService.SendEmailAsync(builder => builder

                .To("[email protected]", "Abdelrahman")
                .Subject("Your Invoice Ready " + i.ToString())
                .Body("this is to inform you that yoyr invoice is ready " + i.ToString())

                );

                await Task.Delay(10);
            }


public async Task<SendResponse> SendEmailAsync(Action<EmailMessageInfoBuilder> builderAction)
        {
            await _lock.WaitAsync();

            SendResponse sendResponse = null;
            EmailMessageInfo emailInfo = null;
            try
            {
                
                EmailMessageInfoBuilder emailInfoBuilder = new EmailMessageInfoBuilder(_fluentEmailFactory);
                builderAction(emailInfoBuilder);

                emailInfo = emailInfoBuilder.EmailMessageInfo;

                IFluentEmail fluentEmail = CreateFluentEmail(emailInfo);
                
                sendResponse = await fluentEmail.SendAsync();

            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, $"Faild to send Email {emailInfo?.ToJSON()}");
            }
            finally
            {
                _lock.Release();
            }

            return sendResponse;


        }

The _lock object is defined as following:

private readonly SemaphoreSlim _lock = new SemaphoreSlim(1, 1);

Very strange behavior occurring, I received one email with

subject => "Your Invoice Ready 1" and body => "this is to inform you that yoyr invoice is ready 1"

and 9 emails with the subject

subject => "Your Invoice Ready 11" and body => "this is to inform you that yoyr invoice is ready 11"

Any suggestions on why this result?

Note: when I remove the lines

await _lock.WaitAsync();
_lock.Release();

it working normally.

0

There are 0 answers