0

I have a Lambda function and that lambda function is supposed to send messages to multiple queues in SQS and then exit,

If I add await, then messages are sent to all queues,

var sqsClient = ServerlessHelper.GetAmazonSqsClient();
foreach (var item in items)
{
    await sqsClient.SendMessageAsync(item.QueueUrl, item.Message);
}

But if I remove await from the code, then none of messages are sent to queues. I want to send messages in parallel. But due to await I have function cannot send messages in parallel. I am trying to do something like this,

var sqsClient = ServerlessHelper.GetAmazonSqsClient();
foreach (var item in items)
{
    sqsClient.SendMessageAsync(item.QueueUrl, item.Message);
}
// wait until are messages are sent to queues.

Is it possible to do this?

fhnaseer
  • 7,159
  • 16
  • 60
  • 112
  • Just because a task is returned does not main that the library is thread safe. `async/await` allow for the current thread to be suspended so it can serve other requests while the IO operation is executed. It has nothing to do directly with TPL. See also [Difference between the TPL & async/await (Thread handling)](https://stackoverflow.com/a/10286513/1260204) – Igor Oct 31 '18 at 16:53

2 Answers2

0

I'm guessing sqsClient.SendMessageAsync(item.QueueUrl, item.Message); returns a Task since it is an async function?

You need to save the task instances then use Task.WhenAll as in this example.

sean
  • 367
  • 2
  • 12
-2

Yes, it is possible like this:

await Promise.all(
    items.map(item => 
        sqsClient.SendMessageAsync(item.QueueUrl, item.Message)
    )
)

The map function will create an array of promises. This array can be wrapped in a single promise by the Promise.all function, for which you can wait. This way, the promises will be resolved concurrently.

stijndepestel
  • 3,076
  • 2
  • 18
  • 22
  • 2
    This is [tag:javascript] (or [tag:typescript]). The question is about [tag:c#] – Igor Oct 31 '18 at 16:52
  • Waauw. Totally did not spot that. I'm sorry. But I'm sure there will be a library or something that will do something similar. I'd try Googling for that. – stijndepestel Oct 31 '18 at 17:14
  • 1
    Maybe but I am not the person that posted the question ;) – Igor Oct 31 '18 at 17:24