Application hangs when sending from MVC Web Applic

2019-08-20 07:18发布

问题:

This is a controller code of an Azure Web App that handles a device notification logic. What I'm doing is invoking the code shown below from a ASP MVC Controller. But when I run it I get an ever-pending request from the browser(it hangs). I have a button on view, when clicked, it invokes Wakeup method in the controller.

The code is not different from the one on MSDN for a console application. What am I missing?

using System.Text;
using Microsoft.Azure.Devices;

 public class MyTemplate2Controller : Controller
    {
        static ServiceClient serviceClient;
        static string connectionString = "HostName=azure-devices.net;SharedAccessKeyName=iothub;SharedAccessKey=mrUPt*2318C18K3LUk+oFarkNQ4vRvHrOa/eg=";

        private AsyncController Task SendCloudToDeviceMessageAsync()
        {
            var asd = "{13A20041677B0,4,15,0}";
            var commandMessage = new Message(Encoding.ASCII.GetBytes(asd));
          return  await serviceClient.SendAsync("Test_Comp_Dev_1", commandMessage).ConfigureAwait(continueOnCapturedContext: false);
        }
        public void Wakeup()
        {

            serviceClient = ServiceClient.CreateFromConnectionString(connectionString);

            SendCloudToDeviceMessageAsync().Wait();
        }

回答1:

try the following:

    public void Wakeup()
    {
        serviceClient = ServiceClient.CreateFromConnectionString(connectionString);

        System.Threading.ThreadPool.QueueUserWorkItem(a => SendCloudToDeviceMessageAsync().Wait());
    }