0

Can someone help me how to make the call to the method SendSms(textMessageItems) asynchronous? What is the best method/practice? I am presuming that Task.Run Async-Await can be used here since I am using .Net4.5 using MVC4 WebApi. But I would like to hear from the experts as I am new to this. I am using this code in my web Server which is in IIS7 and this method could take sometime to process and so would like to process it asynchronously so that the response can return right away to the caller. Also since I am calling the SendSms inside a for loop would it cause any issue? Do you think I should pass it as a collection List and then process? Please advise.

 using Twilio.Mvc;
 using Twilio.TwiML.Mvc;
 using Twilio.TwiML;


public class SmsController : ApiController
{
    [HttpPost]
    public HttpResponseMessage Post([FromBody]SmsRequest smsReq)
    {
            var response = new Twilio.TwiML.TwilioResponse();
            //validation checks..

            try
            {


                if ((txtMessageResponse != null) && (txtMessageResponse.SmsMessageInfo.Count > 0))
                {
                    _smsStagingList = txtMessageResponse.SmsMessageInfo;
                    foreach (TextMessageStaging prepareTextMessageResponse in _smsStagingList)
                    {
                        smsDTO textMessageItems = new smsDTO();
                        textMessageItems.PhoneNumber = prepareTextMessageResponse.PhoneNumber;
                        textMessageItems.SmsMessage = prepareTextMessageResponse.SmsMessageBody;

                        isTxtMessageSent = SendSms(textMessageItems);

                        //If the messages were sent then no need to set the flag to be updated 
                        if (isTxtMessageSent)
                        {
                            txtMessageStatusToBeUpdated = false;
                        }
                    }
                    return Request.CreateResponse(HttpStatusCode.OK, twilioResponse.Element);
                }
                else
                {
                    //send error response
                }
            catch (Exception msgProcessingError)
            {
              //send error response again as processing error
            }
            finally
            {
             //set the outbound flag in the table
            }
     }


    private bool SendSms(smsDTO textMessageItems)
    {
        bool isTxtMessageSent = false;
        PushMessageRequest txtMessageRequest = new PushMessageRequest();
        PushMessageResponse txtMessageResponse = null;
        txtMessageRequest.SmsMessageInfo = new SendTextMessage(); //instantiate the dto

        txtMessageRequest.SmsMessageInfo.ToPhone = textMessageItems.PhoneNumber;
        txtMessageRequest.SmsMessageInfo.TextMessage = textMessageItems.SmsMessage;
        try
        {
            using (ITextService textService = ObjectFactory.SendSmsMessage())
            {
                txtMessageResponse = textService.SendSmsMessage(txtMessageRequest);
            }

            isTxtMessageSent = txtMessageResponse.IsSuccessful;
        }
        catch (Exception ex)
        {
            isTxtMessageSent = false;
        }      
        return isTxtMessageSent;
    }          

1 Answer 1

1

I recommend that you not use Task.Run. AFAIK, Twilio does not have an async API, so you should ask them about that. You could of course write your own, e.g., based on HttpClient.

would like to process it asynchronously so that the response can return right away to the caller

Please note that async does not change the HTTP protocol, as described on my blog. It is possible, but extremely dangerous, to return a response from ASP.NET while the request has not finished processing (also a link to my blog).

Sign up to request clarification or add additional context in comments.

6 Comments

Actually the response would only be an HTTP OK response and nothing else. The reply to the incoming text is sent via an outgoing text and it is actually not tied up to the incoming text. That part is taken care of by the textService.SendSmsMessage. Does that make sense?
@Ditty: Yes, and my advice still stands. It is still extremely dangerous. Your web service should just store the request data into a reliable queue (e.g., Azure queue / MSMQ) and have a separate backend processes send the SMS responses (e.g., Azure worker role / Win32 service).
So even if it is a fire and forget kind of call would you still advise the same? I saw in your article blog.stephencleary.com/2012/12/… under the Q&A you mentioned something about using an Async with await. Will that anyways work here or still not recommended?
@Ditty: You can use async and await just fine. But it won't return a response to the caller.
You mean the server will wait for the asynch process to complete due to await before it will send the HTTP response back? Is that what you meant?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.