简体   繁体   中英

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. 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
Successfully sent to Elvis Pressley
There was a problem sending to 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". 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.

As for how you get that information back to the client, an UpdatePanel will probably be your best bet.

Light reading on yield keyword

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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