I have the following function, based on a question I asked a while back here:
How to allow to open multiple instances of a Form under certain specified condition?
public void AbrirFormulario<T>(Func<T> metodofactory,string textoForm = "", bool multiplesInstancias=false) where T : Form
{
//Buscar el formulario dentro del panel.
Form formulario;
if (string.IsNullOrEmpty(textoForm))
formulario = panel_contenedor.Controls.OfType<T>().FirstOrDefault();
else
formulario = panel_contenedor.Controls.OfType<T>().Where(f => f.Text.Equals(textoForm)).FirstOrDefault();
if (formulario != null)
{
if (string.IsNullOrEmpty(Convert.ToString(formulario.Tag)) ||
(bool)formulario.Tag==false || formulario.Text == textoForm)
{
//Si la instancia esta minimizada la dejamos en su estado normal
if (formulario.WindowState == FormWindowState.Minimized)
{
formulario.WindowState = FormWindowState.Normal;
}
//Si la instancia existe la pongo en primer plano
formulario.BringToFront();
return;
}
}
//Se abre el form
formulario = metodofactory();
formulario.TopLevel = false;
if (multiplesInstancias == true)
formulario.Tag = multiplesInstancias;
if (multiplesInstancias == true && !string.IsNullOrEmpty(textoForm))
formulario.Text = textoForm;
panel_contenedor.Controls.Add(formulario);
panel_contenedor.Tag = formulario;
formulario.BringToFront();
formulario.Show();
}
Which works perfectly fine, but when executing it for example:
AbrirFormulario(() => new Form1(true, "parametro2"), "Titulo", true);
Until the function does not finish doing all the validations, my interface (UI) is blocked, I would like to start using (Async, Await, Task) in this function so that when the function is executed it works, and I can continue using my Interface.
That said, can you help me adapt this function to work with (Async, Await, Task) to work in parallel?
My current work environment is: Visual Studio 2017 with .NetFrameWork 4.5.2
Note: I've never used (Async, Await, Task), it's a bit difficult for me to understand, and I'd like to start with this function to understand how it works.
It occurs to me that to solve your problem, you can use Task.Run together with async/await and validating InvokeRequired when necessary
Now to call the function, for example on a button
Edit: When it comes to duplicating the code, what comes to my mind is to use a function, something like this:
Then later, when you need, you directly call it like this