为什么在调用Invoke时遇到异常?

时间:2017-03-08 16:02:20

标签: c#

我尝试在表单上调用ArgumentOutOfRangeException函数时得到Invoke()。我使用委托模式来避免非法的跨线程调用,因为addAgentToList()函数被另一个线程(不是处理GUI的线程)调用。

为什么我会收到以下异常?

enter image description here

    public void addAgentToList(Agent agent) {
        if(lstAgents.InvokeRequired) {
            OnAddAgentToList callback = new OnAddAgentToList(addAgentToList);
            this.Invoke(callback, new object[] { agent });
        } else {
            lstAgents.BeginUpdate();
            try {
                if(!isAgentOnList(agent)) {
                    ListViewItem item = new ListViewItem(agent.Name+" @ "+agent.Address.ToString());
                    item.Tag = agent;
                    item.ImageIndex = 0;
                    lstAgents.Items.Add(item);
                }
            } finally {
                lstAgents.EndUpdate();
            }
            // select agent
            if(lstAgents.SelectedIndices.Count==0) {
                if(lstAgents.Items.Count>0) {
                    lstAgents.Items[0].Selected = true;
                }
            }
        }
    }

    private bool isAgentOnList(Agent agent) {
        foreach(ListViewItem item in lstAgents.Items) {
            Agent listAgent = (Agent)item.Tag;
            if(agent==listAgent) {
                return true;
            }
        }
        return false;
    }

以下是文本表示的例外:

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in System.Windows.Forms.dll

Additional information: Value of '1' is not valid for 'Value'. 'Value' should be between 'Minimum' and 'Maximum'.

0 个答案:

没有答案