Apologies as I know cross-thread operations have been addressed elsewhere, but all I see are fragments and can't quite figure out where to apply the solutions correctly. So I have distilled this problem to it's most basic essence in the hope that me and anybody else who comes across this can see a complete solution without a lot of support code to wade through or fragments with limited context. I have looked at various posts such as here, here and here but can't quite place the solutions in context.
I have created a Windows Forms project with a single button and textbox. In the form.cs file here is the complete code to demonstrate the problem:
using System;
using System.Windows.Forms;
using System.Threading;
namespace SampleEventTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
TestClass();
}).Start();
}
private void TestClass()
{
TestEvent tv = new TestEvent();
tv.OnClsConnect += new TestEvent.clsConnect(OnConnected);
tv.DoSomethingThread();
}
public void OnConnected(string str)
{
textBox1.Text = str;
}
}
public class TestEvent
{
public delegate void clsConnect(string str);
public event clsConnect OnClsConnect;
public void DoSomethingThread()
{
if (OnClsConnect != null)
{
OnClsConnect("Thread run");
}
}
}
}
Click the button and you will get the "Cross thread operation not valid" error. How does one properly fix this code? TIA