cnd*_*cnd 12 .net c# thread-safety winforms
我有一个模块,用于串行端口sygnal的事件
serialPort.DataReceived.AddHandler(SerialDataReceivedEventHandler(DataReceived));
Run Code Online (Sandbox Code Playgroud)
DataReceived的位置
let DataReceived a b =
rxstring <- serialPort.ReadExisting()
arrayRead <- System.Text.Encoding.UTF8.GetBytes(rxstring)
if arrayRead.[0] = 0x0Auy then
ProcessData(a, null)
Run Code Online (Sandbox Code Playgroud)
和ProcessData正在调用WinForms方法
let ProcessData(a, b) =
dataProcessor.Invoke(a, b) |> ignore
Run Code Online (Sandbox Code Playgroud)
是的
private void ProcessData(object sender, EventArgs e) {
byte[] m = Core.ncon.ArrayRead;
switch (m[1]) {
case 0x01: {
if (m.Length > 5) {
int myval = BitConverter.ToInt32(m, 3);
textBox1.Text += " val: " + myval.ToString() + " ";
Run Code Online (Sandbox Code Playgroud)
但是当它试图访问textBox1时我得到了:
跨线程操作无效:控制'textBox1'从其创建的线程以外的线程访问.
所以问题是如何从另一个模块事件中访问WinForm元素?
Pho*_*cUK 17
您需要使用表单调度程序.
FormContaingTheTextbox.Invoke(new MethodInvoker(delegate(){
textBox1.Text += " val: " + myval.ToString() + " ";
}));
Run Code Online (Sandbox Code Playgroud)
这使得代码在表单线程中而不是在您的表单中运行.
Moh*_*han 13
尝试使用以下代码:
this.Invoke(new MethodInvoker(delegate()
{
//Access your controls
}));
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助