I am trying to find a way to change the parent of a thread of a winform back to the GUI thread. Right now i have to create the form from another thread but accessing become impossible from the main form that has the reference to it.
here a sample of what i have
public partial class MainForm : Form
{
// local instance of the sub form
private ViewForm SubForm { get; set;} = null;
public MainForm()
{
InitializeComponent();
Task.Run(() =>
{
// set the sub form
SubForm = new ViewForm();
}
// call the rest of the initialization of main form
InitializeCustomControls();
}
private void OpenViewWindow_Click(object sender, EventArgs e)
{
// if the window is instanciated
if (SubForm != null)
{
SubForm.Show();
}
}
}
The ViewForm
window is not a Form
object. it's a custom third party window. It has a lot of controls and templates mixed with themes. The sole call to a new empty constructor can take up to 7 seconds hence why i need to create it on another thread while i continue loading my main window.
Right now i can call any method in the window except .Show()
which always fail due to thread creation restriction. I would like to stay away from creating the thread as an endless running thread that will wait and read some object to will tell him when to show and hide the window.
the is the .Show()
error :
Cross-thread operation not valid: Control 'ViewForm' accessed from a thread other than the thread it was created on.
I did try the following instead but it still freeze my interface :
Task.Run(() =>
{
// set the sub form
this.Invoke(new MethodInvoker(delegate
{
SubForm = new ViewForm();
}));
}
What i would like is something like a fire and forget instantiation of a GUI object.