I have a module whith an event for serial port sygnal
serialPort.DataReceived.AddHandler(SerialDataReceivedEventHandler(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)
and ProcessData is invoking WinForms method
let ProcessData(a, b) =
dataProcessor.Invoke(a, b) |> ignore
which is
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() + " ";
but when it's trying to access textBox1 I'm getting:
Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on.
So the question is How to access WinForm elements from another module events?
Gets a value indicating whether the caller must call an invoke method when making method calls to the control because the caller is on a different thread than the one the control was created on. public: property bool InvokeRequired { bool get(); }; C# Copy.
Multithreading can improve the performance of Windows Forms apps, but access to Windows Forms controls isn't inherently thread-safe. Multithreading can expose your code to serious and complex bugs.
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.
Try Using below Code:
this.Invoke(new MethodInvoker(delegate()
{
//Access your controls
}));
hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With