1

Possible Duplicate:
Cross-thread exception when setting WinForms.Form owner - how to do it right?

I'm newbie to C# Windows Forms Application Development.

In my application main form we create new forms in other thread like below.

Task.Factory.StartNew(
            () =>
            {
                PlotForm plotForm = new PlotForm();
                Application.Run(plotForm);
            });

I want to display that forms always on top of the main form. There is a topmost property in Forms. If i set it to true they are also on top of the other forms.

In the internet it is said that solution is to set owner property and when i set this property , i got cross thread operation because forms are created different threads.

Task.Factory.StartNew(
            () =>
            {
                PlotForm plotForm = new PlotForm();
                plotForm.Owner = this;
                Application.Run(plotForm);
            }); 

Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.

Do you know a solution?

Thanks.

Community
  • 1
  • 1
jacop41
  • 152
  • 7
  • 25
  • 2
    Why you need to run in different thread? – cuongle Oct 14 '12 at 09:12
  • 1
    This is the only case I know where the cross-threading check is not accurate. Windows does in fact support this. Running a form on a thread-pool thread however is *not* supported, the thread must be an STA apartment. A plain Thread object and a call to its SetApartmentState method is required. Don't do this. – Hans Passant Oct 14 '12 at 11:30

1 Answers1

1

For cross thread operations you need to use Invoke. The "invoke" call tells the form "Please execute this code in your thread rather than mine."

Task.Factory.StartNew(
            () =>
            {
                PlotForm plotForm = new PlotForm ();
                this.Invoke((MethodInvoker)delegate()
                {                   
                   plotForm.Owner = a;
                   plotForm.Show();
                });
            }); 
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185