跨线程操作无效(如何从另一个模块事件访问WinForm元素?) [英] Cross-thread operation not valid (How to access WinForm elements from another module events?)

查看:42
本文介绍了跨线程操作无效(如何从另一个模块事件访问WinForm元素?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模块,其中有一个用于串行端口sygnal的事件

I have a module whith an event for serial port sygnal

serialPort.DataReceived.AddHandler(SerialDataReceivedEventHandler(DataReceived));

DataReceived为

where DataReceived is

let DataReceived a b =
    rxstring <- serialPort.ReadExisting()
    arrayRead <- System.Text.Encoding.UTF8.GetBytes(rxstring)
    if arrayRead.[0] = 0x0Auy then
        ProcessData(a, null)

ProcessData正在调用WinForms方法

and ProcessData is invoking WinForms method

let ProcessData(a, b) =
    dataProcessor.Invoke(a, b) |> ignore

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() + " ";

但是当它尝试访问textBox1时,我得到了:

but when it's trying to access textBox1 I'm getting:

跨线程操作无效:控制'textBox1'是从创建该线程的线程之外的线程访问的.

所以问题是如何从另一个模块事件访问WinForm元素?

So the question is How to access WinForm elements from another module events?

推荐答案

您需要使用表单分派器.

You need to use the forms dispatcher.

FormContaingTheTextbox.Invoke(new MethodInvoker(delegate(){
    textBox1.Text += " val: " + myval.ToString() + " ";
}));

这使该代码在表单线程中而不是您的线程中运行.

This makes that code run in the forms thread instead of yours.

这篇关于跨线程操作无效(如何从另一个模块事件访问WinForm元素?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆