为什么这个backgroundworker代码导致此错误:参数计数不匹配

时间:2010-02-20 03:28:17

标签: c# multithreading begininvoke

下面的代码有什么问题? conn_PageDeleted来自后台线程,我每次收到回拨时都会尝试更新标签。我收到一条错误说明

参数计数不匹配。

以下是代码:

    private void cmdDeletePage_Click(object sender, EventArgs e)
    {
         worker = new BackgroundWorker();
         worker.DoWork += new DoWorkEventHandler(worker_DoWork);
         worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
         worker.RunWorkerAsync();
    }

    void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        lblDeleteStatus.Text = "";
        MessageBox.Show("Complete");
    }

    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        Connecter conn = new Connecter("a", "m");
        conn.PageDeleted += new Connecter.PageDeletedHandler(conn_PageDeleted);
        bool success = conn.DeletePage(txtPageToDelete.Text, chkRecursive.Checked);
    }


    public delegate  void UpdateLabelHandler(object sender, string name);

    void conn_PageDeleted(object sender, string name)
    {
        if (this.InvokeRequired)
        {
            this.BeginInvoke(new UpdateLabelHandler(UpdateMe));
        }
        else
        {
            lblDeleteStatus.Text = name;                
        }
    }

    private void UpdateMe(object sender_, string name_)
    {
        lblDeleteStatus.Text = name_;
    }

2 个答案:

答案 0 :(得分:2)

您应该将参数传递给UpdateMe方法,试试这个:

void conn_PageDeleted(object sender, string name)
    {
        if (this.InvokeRequired)
        {
            this.BeginInvoke(new UpdateLabelHandler(UpdateMe), new object[] {sender, name}); //<-- the update goes here
        }
        else
        {
            lblDeleteStatus.Text = name;                
        }
    }

答案 1 :(得分:1)

您的委托必须匹配事件处理程序的签名,如下所示:

public delegate void UpdateLabelHandler(object sender, string strArgs);

编辑:由于您已编辑代码以包含此内容...我将相应修改此内容.... 看看你编辑过的代码,我不得不质疑:

    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        Connecter conn = new Connecter("a", "m");
        conn.PageDeleted += new Connecter.PageDeletedHandler(conn_PageDeleted);
        bool success = conn.DeletePage(txtPageToDelete.Text, chkRecursive.Checked);
    }

你正在连接一个'PageDeleted'事件处理程序....并在它之后调用'DeletePage'方法,我认为反过来调用'DoWork'体内的事件处理程序'conn_PageDeleted',它超出了范围当'BackgroundWorker'线程完成时...并且因为'conn'在'worker_DoWork'方法的本地范围内,它会被破坏,并且某种程度上你的事件处理程序搞砸了!你能证实一下吗?

希望这有帮助, 最好的祝福, 汤姆。