我目前正在尝试为我的 IoT 学校项目开发简单的 Web 应用程序。至于现在它应该只从我的 Raspberry 调用直接方法。我正在为 C# 使用 Azure SDK。这是代码的样子:控制器: public ActionResult changeState(int? id, bool enable) { string conn_str = (from u in db.Users join h in db.Hubs on u.Hub.HubId equals h.HubId where u.UserName == User.Identity.Name select h.connection_str).First(); Cloud2Device c2d = new Cloud2Device(conn_str); if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Rp rp = db.Rps.SingleOrDefault(r => r.RpId == id); if (rp == null) { return HttpNotFound(); } //IoT stuff try { c2d.EnableRaspberry("myDeviceId").Wait(); } catch(Exception ex) { //do something } rp.is_enabled = enable; db.SaveChanges(); return RedirectToAction("Index"); }物联网应用:public class Cloud2Device{ private ServiceClient s_serviceClient; public Cloud2Device(string conn_str) { s_serviceClient = ServiceClient.CreateFromConnectionString(conn_str); } public async Task EnableRaspberry(string deviceId) { var methodInvocation = new CloudToDeviceMethod("EnableRaspberry") { ResponseTimeout = TimeSpan.FromSeconds(2) }; var response = await s_serviceClient.InvokeDeviceMethodAsync(deviceId, methodInvocation); Debug.WriteLine(response.GetPayloadAsJson()); }}问题是,从调试输出中我可以看到异常 Microsoft.Azure.Devices.Common.Exceptions.DeviceNotFoundException 被抛出,但是它没有被 try-catch 块处理。
1 回答

ABOUTYOU
TA贡献1812条经验 获得超5个赞
我不确定错误输出实际上是向您的代码抛出的异常。它可能是 ApplicationInsights 只是记录。 但是,我认为由于调用Wait
和阻止了异步方法的返回,代码被冻结了。
使控制器方法返回 type Task<ActionResult>
,使该方法async
,然后用于await c2d.EnableRaspberry("myDeviceId");
调用该方法。
看看这样做是否会导致异常(或成功)。
- 1 回答
- 0 关注
- 149 浏览
添加回答
举报
0/150
提交
取消