问题
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?
回答1:
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.
回答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.
来源:https://stackoverflow.com/questions/53085252/qqsclient-sendmessageasync-without-await-doesnt-work