Call async method from MVC

I am trying to send an asynchronous SMS from an MVC5 controller.

In the controller, I call the following method, which is in another class. I don’t need any answer from the method, and I don’t care if it works.

public async void SendSMS(string phoneNumber, string message) { await Task.Run(() => { TwilioRestClient twilio = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN); twilio.SendSmsMessage(TWILIO_PHONE_NUMBER, phoneNumber, message); } ); } 

This does not work for me as it works synchronously. Any advice on how to improve the code and get it working is appreciated.

+7
asp.net-mvc asp.net-mvc-5 async-await
source share
1 answer

When you await a Task (or any other awaitable ), you tell the compiler, "I am awaitable this task and returning control to you." What happens is that the control is returned to the receiver until Task finishes execution, and the compiler creates a state machine that returns to await after it finishes.

In your method, you do not need any of this.

I will declare that I am not a fan of the fire and forgetting methods, and I think you should add a sequel to deal with the failure of Tasks, even if you don't care if he succeeds. If you use .NET 4.0 without handling the Task exception, this will end your process when the finalizer has the Task .

You can remove async from your method signature since you don't need await and return Task instead:

 public Task SendSMS(string phoneNumber, string message) { return Task.Run(() => { TwilioRestClient twilio = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN); twilio.SendSmsMessage(TWILIO_PHONE_NUMBER, phoneNumber, message); }); } 
+6
source share

All Articles