代码如下
string serialreadstring;
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
serialreadstring += serialPort1.ReadExisting();
this.textBox1.Invoke
(
new MethodInvoker
(
delegate
{
this.textBox1.AppendText(serialreadstring);
}
)
); }
请问这段代码是什么意思?特别是this.textBox1.Invoke
(
new MethodInvoker
(
delegate
{
this.textBox1.AppendText(serialreadstring);
}
)
这一部分!
string serialreadstring;
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
serialreadstring += serialPort1.ReadExisting();
this.textBox1.Invoke
(
new MethodInvoker
(
delegate
{
this.textBox1.AppendText(serialreadstring);
}
)
); }
请问这段代码是什么意思?特别是this.textBox1.Invoke
(
new MethodInvoker
(
delegate
{
this.textBox1.AppendText(serialreadstring);
}
)
这一部分!
private void portcode_check(SerialPort ports, int num)
{
if (ports.IsOpen)
{
string str = "";
try
{
System.Threading.Thread.Sleep(50);
str = ports.ReadExisting();
}
catch
{
System.Threading.Thread.Sleep(50);
try
{
str = ports.ReadExisting();
}
catch { return; }
}
if (str.Length >= 21)
{
if (!V_Regex.isNumber(str.Substring(0, 1))) //判断第一个字符是否为数字.通常光栅扫描带有前缀.
str = str.Substring(1, 20);
else
str = str.Substring(0, 20);
if (!V_Regex.isNumber(str))
return;
code_check(str, num);
}
}
}
这是我在做条码扫描是写的,希望对你有用,方法的第一个参数是串口控件,第二个参数你可以去掉,最好一句code_check(str, num)是一个方法。
上面你说的 new MethodInvoker 这个东西是线程方面的知识,这样做是为了不让那个textbox获取值的时候不会出问题,其实还有一种写法:delegate void ShowTextBoxHandler(TextBox txt, string str);
private void ShowTxt(TextBox txt, string str)
{
if(txt.Invoker)
{
ShowTextBoxHandler s = new ShowTextBoxHandler(ShowTxt);
this.Invoker(s, new object[]{txt, str});
}
else
{
this.textBox1.AppendText(str);
}
}
这个和上面你看到的效果是一样的,不过这样会好理解一些,有空去看看线程方面的知识吧!对于硬件方面的操作很多都会用到线程。
因为UI上的所有控件都是在UI线程上工作,与UI线程是绑定的,其它线程无权访问,如果需要使用,则必须
使用invoke方法,提交代码段由UI线程去执行,从而使得子线程可以访问UI线程的控件。
还有一个BeginInvoke方法也是一样,Invoke是同步执行,而BeginInvoke是异步不止,具体参考msdn。
IAsyncResult ia = dealHander.BeginInvoke(client, null, null);
if (ia.IsCompleted)
{
dealHander.EndInvoke(ia);
}this.Invoke(new Action<object>(delegate(object o)
{
lblStatus.Text = msg;
}), new object[] { null });
当然 你也可以设置Form的 CheckForIllegalCrossThreadCalls 属性为false(不安全)