2

有没有办法可以内联委派任务而不是将其分离到另一个函数上?

原始代码:

    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
        }
    }

我希望它是这样的(无需创建单独的函数):

    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());
    }
4

2 回答 2

4

我认为这会起作用:

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());
}

您需要做的就是在声明匿名方法的行之前为“attach”(null 有效)分配一个值。我确实认为前者更容易理解。

于 2009-06-26T03:31:19.490 回答
0

您收到“使用未分配变量”错误的原因是编译器实际生成代码的方式。当您使用 delegate{} 语法时,编译器会为您创建一个真正的方法。由于您在委托中引用附加字段,因此编译器会尝试将局部变量传递attach给生成的委托方法。

这是粗略翻译的代码,应该有助于使其更清晰:

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
    }
}

请注意,它在初始化之前将附加字段传递给 _b<>_1 方法。

于 2009-06-26T04:51:48.870 回答