作者james999 (无伤大雅)
看板C_Sharp
标题[问题] StreamSocket类别放在成员变数可行吗?
时间Fri Dec 22 10:24:16 2017
会这麽问..
是因为手边一支可运行的程式,
收到uart的讯号後会立即调用StreamSocket区域变数,
开socket将资料丢出,完成後关闭。
但是仅仅只是将StreamSocket改为成员变数,
将new及其他connectAsync..等相关函式拿掉,没有进行任何操作,
在本来程式运行一开始时的开串列埠时,就会崩溃...
有任何能协助我的地方吗? 谢谢喔:)
--
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 220.132.128.217
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_Sharp/M.1513909459.A.014.html
1F:推 YahooTaiwan: 崩溃的话应该要看医生 12/22 10:37
2F:→ YahooTaiwan: 造成 Crash 的 Exception 是什麽阿?? 12/22 10:38
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
3F:→ smmoon: FindallAsync 找不到所以null? 12/22 13:03
※ 编辑: james999 (220.132.128.217), 12/22/2017 13:33:40
4F:→ james999: FindallAsync不会crash,但会在该行的下方随机某行crash 12/22 13:40
5F:→ smmoon: 传回IAsyncOperation<DeviceInformationCollection> 12/22 16:07
6F:→ smmoon: 如果dis.count == 0 那你的dis[0] 就有问题了 12/22 16:07
7F:→ james999: 问题在每次看count都是1... 甚至有时候还没机会到那行 12/22 16:55
8F:→ james999: 在var dis时就崩溃了 Orz 12/22 16:55
9F:→ james999: 把和所有有关clientSocket的操作全拿掉後,只留下.. 12/22 16:56
10F:→ james999: StreamSocket clientSocket = null;这行,还是会有问题 12/22 16:57
11F:→ james999: 只要把StreamSocket clientSocket = null;拿掉即正常 12/22 16:57
12F:→ smmoon: 检察看看硬体先 12/22 17:02
13F:→ smmoon: 把错误的讯息都记下来 一个个解 12/22 17:02
14F:推 YahooTaiwan: 你给的程式码好像没有写到 clientSocket = null 12/22 17:58
15F:→ james999: 因为clientSocket = null放在成员变数的区块里@@ 12/23 12:53
问题解决了,不要把new StreamSocket和开com port的程式写在一块就..没事!!
具体等有空再查查,谢谢各位^^
※ 编辑: james999 (36.230.202.136), 12/23/2017 13:22:53