简体   繁体   English

每次迭代ASP.NET时,从C#循环将值异步发布到客户端

[英]Post value from C# loop to client asynchronously every time loop iterates ASP.NET

I'm using Twilio to send out text messages using an ASP.NET web app. 我正在使用Twilio通过ASP.NET Web应用程序发送文本消息。 I'm using a Post-Redirect after the submit button is pressed to send the message. 按下提交按钮发送消息后,我正在使用后重定向。 When the second page fully loads, I want to update the client for every time a message is sent, and show the result and the recipient. 当第二页完全加载后,我想在每次发送消息时更新客户端,并显示结果和收件人。 This will need to be async, avoiding a page refresh or post back. 这将需要异步处理,以避免刷新页面或发回页面。 What would be the best way to handle updating the client every time the method loops, and return the result and recipient? 每次方法循环时处理客户端更新并返回结果和接收者的最佳方法是什么? I want to append the recipients in the UI to show who is receiving the message. 我想在用户界面中附加收件人,以显示谁在接收消息。 Similar to this: 与此类似:

Your message is being sent... 您的消息正在发送中...

Successfully sent to John Doe 成功发送给John Doe
Successfully sent to Elvis Pressley 成功发送给猫王出版社
There was a problem sending to Grace Hopper 发送给Grace Hopper时出现问题

    foreach (var recipient in recipients)
    {
        SendMessage(recipient);
    }

    public string SendMessage(Recipient recipient)
    {
        // I want to update the client with either of these return statements
        // every time the method is called in the loop.
        if (twilioMessage.Send(recipient.PhoneNumber, message)
        {
            return "Successfully sent to " + recipient.Name;
        }
        else
        {
            return "There was a problem sending to " + recipient.Name;
        }
    }

For the method that contains the for loop, it should have an IEnumerable return type and you should use the keyword "yield". 对于包含for循环的方法,它应具有IEnumerable返回类型,并且应使用关键字“ yield”。 Your code would look something like this: 您的代码如下所示:

public IEnumerable<string> DoMyThing()
{
    foreach (var recipient in recipients)
    {
        yield return SendMessage(recipient);
    }
}

then when you call "DoMyThing()" and get an IEnumerable back every time you move to the next element, execution is returned to the function and the next message will attempt to be sent, you will recieve the result, and you can do a thing with it. 然后,当您调用“ DoMyThing()”并在每次移至下一个元素时获取IEnumerable时,将执行返回到函数,并且将尝试发送下一条消息,您将收到结果,然后可以执行事情。

As for how you get that information back to the client, an UpdatePanel will probably be your best bet. 至于如何将这些信息返回给客户端,UpdatePanel可能是最好的选择。

Light reading on yield keyword 轻率阅读收益率关键字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM