c # error when calling a Thread class from my main class

0
  

The thread consists of moving the gif

    private void btn_start_Click(object sender, EventArgs e)
    {
        if (nuevo == true)//si es la priemra vez que has pulsado el boton
        {

            //pedir datos del personaje
            hilo_motor_GIF hilo = new hilo_motor_GIF(muñecoWalker,2);
            hilo.arrancar();
            nuevo = false;
            btn_start.Text = "Seguir aventura";
        }

        else {
            //accionar el personaje

            //accion();
            hilo_motor_GIF hilo = new hilo_motor_GIF(muñecoWalker, 2);
            hilo.arrancar();
        }
    }

thread class

    using System;
using System.Threading;
using System.Windows.Forms;


public class hilo_motor_GIF
{
    Thread hilo;
    int segundos;
    PictureBox gif;

    public hilo_motor_GIF(PictureBox gif, int segundos)
    {

        this.segundos = segundos;
        this.gif = gif;

        hilo = new Thread(go);
    }

    private  void giffOn() {
        this.gif.Enabled = true;
    }

    private void giffOff() {
        this.gif.Enabled = false;
    }

    public void go() {

        try
        {
            giffOn();
            Thread.Sleep(segundos * 1000);
            giffOff();

        }
        catch (Exception e) {
            Console.WriteLine("Error: "+e);
        }



    }

    public void arrancar() {
        this.hilo.Start();
    }
}

OUTPUT

  

Exception produced: 'System.InvalidOperationException' in System.Windows.Forms.dll   Error: System.InvalidOperationException: Invalid operation through threads: The 'dollWalker' control was accessed from a subprocess other than the one in which it was created.      in System.Windows.Forms.Control.get_Handle ()      in System.Windows.Forms.Control.OnEnabledChanged (EventArgs e)      in System.Windows.Forms.PictureBox.OnEnabledChanged (EventArgs e)      in System.Windows.Forms.Control.set_Enabled (Boolean value)      in thread_motor_GIF.giffOn () in H: \ PROJECTS C # \ CaminanteRandom \ CaminanteRandom \ hilo_motor_GIF.cs: line 21      in hilo_motor_GIF.go () in H: \ PROJECTS C # \ CaminanteRandom \ CaminanteRandom \ hilo_motor_GIF.cs: line 32   Subprocess 0x1154 ended with code 0 (0x0).   The program '[1232] CaminanteRandom.exe' ended with code 0 (0x0).

    
asked by josanangel 04.08.2018 в 20:20
source

1 answer

4

To modify them from a different thread you need to use Invoke. Invoke executes the last method as delegate in the same control thread.

Example:

private  void giffOn() {
{
    this.gif.Invoke((MethodInvoker)delegate () { this.gif.Enabled = true; });
}

Alternatively you can use the BackgroundWorker component that allows you to do the same in a simpler way.

BackgroundWorker includes the event ProgressChanged running on the thread of the component so you do not have to use Invoke and the method ReportProgress to call the event.

    
answered by 05.08.2018 в 04:23