串口
用c#写的串口程序窗体为何会卡,那位指教指教,我刚学。窗体很简单只有一个serialport,一个button,一个richtextbox
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace serialPort
{
public partial class Form1 : Form
{
Thread thethread ;
public Form1()
{
InitializeComponent();
serialPort1.Open();//打开串口
}
private void button1_Click(object sender, EventArgs e)
{
serialPort1.WriteLine(this.richTextBox1.Text);
this.richTextBox1.Text = "";
thethread.Join();
}
public void sar()
{
MethodInvoker mi = new MethodInvoker(var);
BeginInvoke(mi);
}
private void var()
{
richTextBox1.Text = "";
richTextBox1.Text = serialPort1.ReadLine();
}
private void Form1_Load(object sender, EventArgs e)
{
thethread = new Thread(new ThreadStart(sar));
thethread.Start();
}
}
}
------解决方案--------------------
晕,没改完,点到了提交按钮,是下面这个才行委托:
public void sar(object sender, EventArgs e)
{
if (this.richTextBox1.InvokeRequired)
{
this.BeginInvoke(new EventHandler(sar), new Object[] { sender,EventArgs.Empty });
}
else
{
richTextBox1.Text = System.Convert.ToString(obj);
}
}
private void var()
{
sar("", EventArgs.Empty);
string line = serialPort1.ReadLine();
sar(line, EventArgs.Empty);
}
private void Form1_Load(object sender, EventArgs e)
{
thethread = new Thread(new ThreadStart(var)); //改var
thethread.Start();
}