[問題] StreamSocket類別放在成員變數可行嗎?

看板C_Sharp (C#)作者 (無傷大雅)時間7年前 (2017/12/22 10:24), 7年前編輯推噓1(1012)
留言13則, 3人參與, 7年前最新討論串1/1
會這麼問.. 是因為手邊一支可運行的程式, 收到uart的訊號後會立即調用StreamSocket區域變數, 開socket將資料丟出,完成後關閉。 但是僅僅只是將StreamSocket改為成員變數, 將new及其他connectAsync..等相關函式拿掉,沒有進行任何操作, 在本來程式運行一開始時的開串列埠時,就會崩潰... 有任何能協助我的地方嗎? 謝謝喔:) -- -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.132.128.217 ※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1513909459.A.014.html

12/22 10:37, 7年前 , 1F
崩潰的話應該要看醫生
12/22 10:37, 1F

12/22 10:38, 7年前 , 2F
造成 Crash 的 Exception 是什麼阿??
12/22 10:38, 2F
System.NullReferenceException... 但是獲取串口的那段代碼並沒有任何修改, -- string aqs = SerialDevice.GetDeviceSelector(); var dis = await DeviceInformation.FindAllAsync(aqs); int i = dis.Count; DeviceInformation entry = (DeviceInformation)dis[0]; clientSocket = new StreamSocket(); HostName serverHost = new HostName(ServerIPAddress); await clientSocket.ConnectAsync(serverHost, ServerPort); try { serialPort = await SerialDevice.FromIdAsync(dis[0].Id); if (serialPort == null) return; serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000); serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000); serialPort.BaudRate = 115200; serialPort.Parity = SerialParity.None; serialPort.StopBits =SerialStopBitCount.One; serialPort.DataBits = 8; serialPort.Handshake = SerialHandshake.None; ReadCancellationTokenSource = new CancellationTokenSource(); //Listen(); -- 可能會在 var dis = await DeviceInformation.FindAllAsync(aqs); int i = dis.Count; DeviceInformation entry = (DeviceInformation)dis[0]; clientSocket = new StreamSocket(); 這其中的每一行都有可能crash.. 是我哪裡用錯了嗎?謝謝 ※ 編輯: james999 (220.132.128.217), 12/22/2017 11:44:00

12/22 13:03, 7年前 , 3F
FindallAsync 找不到所以null?
12/22 13:03, 3F
※ 編輯: james999 (220.132.128.217), 12/22/2017 13:33:40

12/22 13:40, 7年前 , 4F
FindallAsync不會crash,但會在該行的下方隨機某行crash
12/22 13:40, 4F

12/22 16:07, 7年前 , 5F
傳回IAsyncOperation<DeviceInformationCollection>
12/22 16:07, 5F

12/22 16:07, 7年前 , 6F
如果dis.count == 0 那你的dis[0] 就有問題了
12/22 16:07, 6F

12/22 16:55, 7年前 , 7F
問題在每次看count都是1... 甚至有時候還沒機會到那行
12/22 16:55, 7F

12/22 16:55, 7年前 , 8F
在var dis時就崩潰了 Orz
12/22 16:55, 8F

12/22 16:56, 7年前 , 9F
把和所有有關clientSocket的操作全拿掉後,只留下..
12/22 16:56, 9F

12/22 16:57, 7年前 , 10F
StreamSocket clientSocket = null;這行,還是會有問題
12/22 16:57, 10F

12/22 16:57, 7年前 , 11F
只要把StreamSocket clientSocket = null;拿掉即正常
12/22 16:57, 11F

12/22 17:02, 7年前 , 12F
檢察看看硬體先
12/22 17:02, 12F

12/22 17:02, 7年前 , 13F
把錯誤的訊息都記下來 一個個解
12/22 17:02, 13F

12/22 17:58, 7年前 , 14F
你給的程式碼好像沒有寫到 clientSocket = null
12/22 17:58, 14F

12/23 12:53, 7年前 , 15F
因為clientSocket = null放在成員變數的區塊裡@@
12/23 12:53, 15F
問題解決了,不要把new StreamSocket和開com port的程式寫在一塊就..沒事!! 具體等有空再查查,謝謝各位^^ ※ 編輯: james999 (36.230.202.136), 12/23/2017 13:22:53
文章代碼(AID): #1QF6pJ0K (C_Sharp)
文章代碼(AID): #1QF6pJ0K (C_Sharp)