0

I know this question has been asked too many times here but I don't seem to get it fixed so I am posting a new one.

I have two forms Form1 and Form2. Form2 is displayed as an overlay on form1 by setting its topmost property to true. I have a class that does the processing thing for form1 and if the required value is found it opens the form2 in STA thread as an overlay on form1 .

However class processing is a continous process if the value is not found for few next seconds then I need to close the already opened form2 which I am unable to do at the moment due to above exception.

Here is my code:

private void runBrowserThread(bool markerFound)
{
    try
    {
        var th = new Thread(() =>
        {
            if (markerFound == true)
            {
                if (Application.OpenForms.OfType<webForm>().Count() == 0)
                {
                    webForm frm = new webForm();
                    frm.Show();
                }

                Application.Run();
            }
            else
            {
                if (Application.OpenForms.OfType<webForm>().Count() == 1)
                {
                    Form fc = Application.OpenForms["webForm"];

                    if (fc != null)
                        fc.Close(); //**This line causes cross thread exception**
                }
            }
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start(); 
    } catch (Exception) 
    {
        //...
    }
}

Any suggestions would be really appreciated.

Rob
  • 26,989
  • 16
  • 82
  • 98
G droid
  • 956
  • 5
  • 13
  • 36
  • This has answered many times, have searched before asking the question? – NASSER Sep 19 '15 at 13:40
  • Your code doesn't even compile and has terrible formatting. At least put some effort into asking a question if you want people to help you. – Rob Sep 19 '15 at 13:42

1 Answers1

5

don't use threads if you don't know what you are doing!

replace the error line with

    fc.Invoke(new MethodInvoker(delegate { fc.Close(); }));

this will fix your error, but you are mixing your working and UI threads completely which will give you way more errors.

user287107
  • 9,286
  • 1
  • 31
  • 47
  • I am a newbie in c# and you are right I dont know much abou threads but I am going to get hold of them now. Thank you so much It solved my issue. – G droid Sep 19 '15 at 13:52