String from a Thread to a Label

0

I have Thread , which generates a "query" (this works in a form other than the main one) and I would like to send a variable of type string (that is generated by the query) to be displayed in a Label that is in the first From (main) automatically when it finishes making the "query" the thread.

I have encintado how to pass data from form to another but in the examples you always have to press a button, or the label or textbox changes only when it opens ( show ).

I do not know if I explain myself, I want something that is more dynamic that at the moment of having an answer I can show it immediately in label of form principal ... I imagine how to activate the event textchange or something like that .

    
asked by Eduardo José Giménez 09.05.2017 в 05:57
source

1 answer

0

You can do it with events:

public class MiFormConThread
{
    public event EventHandler CuandoTerminaMiThread;

    void MiThread()
    {
        (new System.Threading.Thread(() =>
            {
                MiConsulta();               

                //#Opción 1
                if (CuandoTerminaMiThread != null)
                    CuandoTerminaMiThread("Mi String", EventArgs.Empty);

                //#Opcion 2 (en C# 6)
                //CuandoTerminaMiThread?.Invoke("Mi String", EventArgs.Empty);

            })).Start();
    }
}

public class MiFormPrincipal
{
    public MiFormPrincipal()
    {
        MiFormConThread form2 = new MiFormConThread();
        form2.CuandoTerminaMiThread += form2_CuandoTerminaMiThread;
    }

    void form2_CuandoTerminaMiThread(object sender, EventArgs e)//sender es el string que pasamos en MiFormConThread
    {
        Invoke((MethodInvoker)delegate
        {
            label1.Text = sender.ToString();

            //C# 6
            //label1.Text = $"{sender}";
        });
    }
}
    
answered by 09.05.2017 / 08:01
source