¿Hay alguna forma en que pueda incorporar una función a un delegado de Acción y hacer referencia a ella al mismo tiempo?

StackOverflow https://stackoverflow.com/questions/1047167

Pregunta

¿Hay alguna forma de alinear la tarea delegada en lugar de separarla en otra función?

Código original:

    private void ofdAttachment_FileOk(object sender, CancelEventArgs e)
    {            
        System.Threading.ThreadPool.QueueUserWorkItem((o) => Attach());
    }

    void Attach() // I want to inline this function on FileOk event
    {

        if (this.InvokeRequired)
        {
            this.Invoke(new Action(Attach));
        }
        else
        {
            // attaching routine here
        }
    }

Quería que fuera así (no es necesario crear una función separada):

    private void ofdAttachment_FileOk(object sender, CancelEventArgs e)
    {

        Action attach = delegate
        {
            if (this.InvokeRequired)
            {
                // but it has compilation here
                // "Use of unassigned local variable 'attach'"
                this.Invoke(new Action(attach)); 
            }
            else
            {
                // attaching routine here
            }
        };

        System.Threading.ThreadPool.QueueUserWorkItem((o) => attach());
    }
¿Fue útil?

Solución

Creo que esto funcionará:

private void ofdAttachment_FileOk(object sender, CancelEventArgs e)
{

    Action attach = null;
    attach = delegate
    {
        if (this.InvokeRequired)
        {
            // since we assigned null, we'll be ok, and the automatic
            // closure generated by the compiler will make sure the value is here when
            // we need it.
            this.Invoke(new Action(attach)); 
        }
        else
        {
            // attaching routine here
        }
    };

    System.Threading.ThreadPool.QueueUserWorkItem((o) => attach());
}

Todo lo que necesita hacer es asignar un valor a 'adjuntar' (nulo funciona) antes de la línea que declara el método anónimo. Sin embargo, creo que lo primero es un poco más fácil de entender.

Otros consejos

La razón por la que obtiene " uso de la variable no asignada " El error se debe a la forma en que el compilador realmente genera el código. Cuando utiliza la sintaxis delegate {}, el compilador crea un método real para usted. Como hace referencia al campo adjunto en su delegado, el compilador intenta pasar la variable local attach al método de delegado generado.

Aquí está el código más o menos traducido que debería ayudar a aclararlo:

private void ofdAttachment_FileOk(object sender, CancelEventArgs e)
{

    Action attach = _b<>_1( attach );

    System.Threading.ThreadPool.QueueUserWorkItem((o) => attach());
}

private Action _b<>_1( Action attach )
{
    if (this.InvokeRequired)
    {
        // but it has compilation here
        // "Use of unassigned local variable 'attach'"
        this.Invoke(new Action(attach)); 
    }
    else
    {
        // attaching routine here
    }
}

Observe que está pasando el campo adjunto al método _b < > _1 antes de que se inicialice.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top