QqsClient.SendMessageAsync without await doesn't work

房东的猫 提交于 2021-01-29 09:55:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!