I have a form.
In that form I create an instance of a class on a new thread because it runs some long running logic. The form also gives the user the ability to cancel this logic/thread.
That class opens a new form if input is required.
The new form sometimes appears behind the other form.
I set a property on the class:
public Form ParentForm{get;set;}
I can now do:
MyForm form = new MyForm();
form.ShowDialog(ParentForm);
However I get a cross thread exception when calling ShowDialog(ParentForm).
I know I can use InvokeRequired somehow but not sure how on a property.
Thanks
UPDATE: Have tried doing this but still get exception:
MyForm form = new MyForm();
form.ShowDialog(GetParentForm());
private Form GetParentForm()
{
//You have to Invoke() so you can wait for the function to return and obtain its return value.
if (ParentForm.InvokeRequired)
{
return (Form)ParentForm.Invoke(new Func<Form>(() => GetParentForm()));
}
else
{
return ParentForm;
}
}
Your updated method (
GetParentForm) won’t work because you’re wrapping the task of getting the reference toParentFormin anInvokeRequiredblock. You could try wrapping theShowDialogcall in such a block instead, but I think you would still get the cross-threading error.Your simplest fix would be to move the code that creates and shows the second form out of your class and into
ParentForm. So instead of this:you would do this:
and in
ParentFormyou would have this:If
MyFormneeds to have a reference to the class on the other thread, you would just add a parameter toshowMyNewForm()so that the reference to it can be passed in.What you’re trying to do here (creating and showing related, connected forms that are created on different threads) is really going against the grain of how forms are meant to be used in .NET.