我目前正在嘗試為我的 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 關注
- 160 瀏覽
添加回答
舉報
0/150
提交
取消