串口接收问题???请教高手!

qlu0634 2008-09-19 11:03:56
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (!R) return;

if (serialPort1.BytesToRead == 0)
{
return;
}
int bytes = serialPort1.BytesToRead;
byte[] buffer = new byte[bytes];
serialPort1.Read(buffer, 0, bytes);
foreach (byte b in buffer)
{
if (b == 0xFF)
{
R = false;
return;
}
string read = System.Text.Encoding.Default.GetString(buffer);
richtextBox1 +=read;
}

}

为什么调试通不过呢?说从不是主线程调用什么的??我是新手 不大懂 希望高手指教!!!在网上还看到关于用什么异步委托来
接收显示数据,看不懂还请高手指点迷津!!
...全文
135 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
jinxuliang 2008-09-21
  • 打赏
  • 举报
回复
vs2003 你的写法没问题
但在vs2005认为用户控件不是线程安全的,就不能那样写了,要用委托.

也用此法来屏蔽的,但一般不推荐
Form.CheckForIllegalCrossThreadCalls = false;


baihe_591 2008-09-20
  • 打赏
  • 举报
回复
可以.
brallow 2008-09-19
  • 打赏
  • 举报
回复
public deleagte void OutputString(string s); //定义委托

//在窗口类里做如下定义:
public OutputString output;
public void RichtTextoutput(string s)
{
richtext.Invoke(output,new object[]{s});
}

//在datareceive中执行
richtextoutput。

不了解你的程序的控件名称之类的,所以大概写了下。
brallow 2008-09-19
  • 打赏
  • 举报
回复
1:在程序加载时使用
Form.CheckForIllegalCrossThreadCalls = false;
先调试一下。
2:异步调用主要是使用invoke。

qlu0634 2008-09-19
  • 打赏
  • 举报
回复
public delegate void MydelegateShow(string read);//声明一个委托
public void UpdateBox(string read)
{
if (this.richTextBox1.InvokeRequired)
{
MydelegateShow SerialDelegate = new MydelegateShow(UpdateBox);
this.Invoke(SerialDelegate, new object[] { read });
}
else
{
this.richTextBox1.Text = read;
}

}
这样写对不???请指教??
baihe_591 2008-09-19
  • 打赏
  • 举报
回复
用委托.



private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (!R) return;

if (serialPort1.BytesToRead == 0)
{
return;
}
int bytes = serialPort1.BytesToRead;
byte[] buffer = new byte[bytes];
serialPort1.Read(buffer, 0, bytes);
foreach (byte b in buffer)
{
if (b == 0xFF)
{
R = false;
return;
}
string read = System.Text.Encoding.Default.GetString(buffer);
// richtextBox1 +=read;
this.Invoke(new EventHandler(delegate { resetText(read); }));//注意这里
}

}
private void resetText(string str)
{
richtextBox1.Text+=str;
}

onekey 2008-09-19
  • 打赏
  • 举报
回复
主窗体上另外的线程不能直接调用主窗体上的控件

3楼的方法可以

qlu0634 2008-09-19
  • 打赏
  • 举报
回复
楼上的仁兄问一下:你看我这样行不??
public delegate void MydelegateShow();//声明一个委托
public MydelegateShow SerialDelegate;//实例化一个委托对象
public Form1()
{
InitializeComponent();
SerialDelegate = new MydelegateShow(UpdateBox);
}
public void UpdateBox(string read)
{
richTextBox1.Invoke(SerialDelegate,new object[]{read}); //显示数据
if (richTextBox1.Text.Length > 1000000)///当接收框中数据太多时,自动清空
richTextBox1.Clear();
}
然后在datareceive中执行UpdateBox(string read)
行不??

110,570

社区成员

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

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

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