4
votes

I know this question has been asked several times, but I can't quite seem to find why it does that in my situation.

First of, I'll explain my program a bit. It connects to a hardware device though a FTDI chip, so it generates us a COM over USB. My programs starts, it's an MDI interface. Clicking Connect brings a connect box similar to the Add Device box in Windows. It scans all COMs on the computer and tries to connect to it, to report what kind of device it is. Afterwards, the user click on a device, connects to it, and a child form opens up to control that device.

So, my problem is, I have a lot of multi-threading going on in there. The first time I connect to my device, it works fine. The second time, it returns a cross-thread operation error.

This is a short example of my code:

    private void ConnectToolStripButton_Click(object sender, EventArgs e)
    {

        Dialogs.Connect Connect = new Dialogs.Connect();
        if (Connect.ShowDialog() == DialogResult.OK)
        {
            this.Connect(Connect.Connection);
        }

    }

    private void Connect(CommunicationInterfaces.Base Connection)
    {

        // Set the connection to the one the connect dialog gave us.
        Child NewConnection = new Child(Connection);

        // Set the parent of the new child and show it.
        NewConnection.MdiParent = this;
        NewConnection.Show(); // CRASH HERE!

    }

So it crashes on the .show() with the following error, but only the second time I connect to it : Cross-thread operation not valid: Control 'Child' accessed from a thread other than the thread it was created on.

Thing is the Child (name of my child form) object is created on the UI thread, if I'm not mistaken. Why does it gives me a cross-thread operation error then? Is it a problem in my child form?

Update: Keep alive timer

So I've been able to pin point the problem a bit more. The problem lies with my Keep Alive thread that I have in my Child's form. To explain the situation: I have a connection which needs to be kept alive, so I have a thread running each 500ms to send a special header to my device. This is my keep alive thread code:

    private void Child_Shown(object sender, EventArgs e)
    {

        this.Connection.DataReceived += DisplayData;

        ...

    }

    private void DisplayData(object Sender, byte[] Data)
    {

        ...

                CreateFaultBox((FaultBoxes.Base.BoxTypes)Data[1]);

        ...

    }

    private void CreateFaultBox(FaultBoxes.Base.BoxTypes BoxType)
    {

        KeepAliveTimer = new System.Threading.Thread(new System.Threading.ThreadStart(this.KeepAlive));
        KeepAliveSwitch = true;
        KeepAliveTimer.Start();

        ...

    }

    private void KeepAlive()
    {

        while (Connection != null && KeepAliveSwitch)
        {

            Console.WriteLine("KEEP ALIVE");

            // Keep the connection alive.
            Connection.KeepAlive();

            // Wait 500ms for the next keep alive.
            System.Threading.Thread.Sleep(500);

        }

    }

If I remove the first 3 lines, so if I don't start the thread, it works without any hiccups. Of couse, KeepAliveSwitch is set to false when I close the form, so the keep alive thread get's terminated after the next 500ms sleep period.

Solution

I changed my keep alive thread to a background worker. Works fine. But I don't get the difference between a thread and a background worker, shouldn't both work the same in this scenario?

1

1 Answers

4
votes

Is any threading going on in the Child form? If so, this is my theory:

What you are likely seeing is a race condition wherein the first time you show a Client, the client form is busy connecting to some device on a background thread, while in the meantime your MDI parent UI thread Show()s the child form (and therefore owns the window handle, and all is good). The second time you show the client, you get a cached connection, and so the background thread in the child very quickly connects and then calls some UI operation, probably checking like a good developer using InvokeRequired(). Since your Client form doesn't yet have a handle, the background thread is getting a false for InvokeRequired, then Invoking and creating the handle itself.

All of this is documented in Ivan Krivyakov's great post on the matter.

So if all of the above sounds right, simply don't start the background work in the Child form until the handle is created. You might want to hang that on the Form Shown event rather than the constructor.