c#关于com口的一些问题

yang830519 2009-09-21 09:04:55
我用C#和ajax实现对com口数据的接受,但是现在有一个问题,我通过按钮来控制com口的打开和关闭状态,但是ajax中的timer控见定时的刷新数据,每一次刷新以后com口总是自动关闭,但是在下一次打开的时候又会出错,本人认为是释放没有完全,但总不能每次刷都重新去打开com口,有没有方法可以一次打开以后就一直打开,直到点击按钮才关闭,希望有高手可以指点,贴一些代码:
SerialPort comm = new SerialPort();
protected void Connect_Click(object sender, EventArgs e)
{

comm.PortName = "COM4";
comm.BaudRate = 9600;
comm.DataBits = 8;
comm.Parity = Parity.None;
comm.StopBits = StopBits.One;
try
{
comm.Open();
if (comm.IsOpen == true)
{
TextBox1.Text = "open";
}
else
{
TextBox1.Text = "not open";
}
comm.DataReceived += new SerialDataReceivedEventHandler(comm_DataReceived);
comm.WriteLine("TEMPA?");
Label1.Text = comm.ReadLine();
comm.WriteLine("TEMPB?");
Label1.Text = comm.ReadLine();
comm.WriteLine("TEMP?");
Label1.Text = comm.ReadLine();
comm.WriteLine("TEMPA?");

Label1.Text = comm.ReadLine();
}
catch { TextBox1.Text = "连接异常"; }

}
...全文
211 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
yang830519 2009-09-21
  • 打赏
  • 举报
回复
具体一点吧!
shalen520 2009-09-21
  • 打赏
  • 举报
回复
用Singleton,静态变量一类的来解决

串口调用代表别写在页面里面,看着恶心~
zhongjiekangping 2009-09-21
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 cpio 的回复:]
要知道ASP.NET运行过程,当页面代码运行完了之后,SerialPort comm 对象就已经没有了
[/Quote]

那可不可以 把状态 保存起来呢
cpio 2009-09-21
  • 打赏
  • 举报
回复
要知道ASP.NET运行过程,当页面代码运行完了之后,SerialPort comm 对象就已经没有了

110,572

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧