C#List.Add System.InvalidOperationException

时间:2018-04-22 21:02:03

标签: c#

我正在处理父表单中的子表单中的事件,当我尝试从处理程序的事件args(下面的代码中的ScraperForm_SiteScraped)中包含的列表中添加项目时,我收到异常System.InvalidOperationException在我的控制台中。

有趣的是,它似乎在第一次添加时成功,但没有后续尝试。

public partial class ProxyTesterView : UserControl
{

    private BindingList<Proxy> proxies = new BindingList<Proxy>();
    private BindingList<ProxyJudge> pudges = new BindingList<ProxyJudge>();
    private BindingList<ProxyTest> tests = new BindingList<ProxyTest>();
    private PauseOrCancelTokenSource pcts = new PauseOrCancelTokenSource();
    private ProxyScraperForm scraperForm = new ProxyScraperForm();

    public ProxyTesterView()
    {
        InitializeComponent();

        proxies.ListChanged += Proxies_ListChanged;
        scraperForm.SiteScraped += ScraperForm_SiteScraped;
    }

    private void Proxies_ListChanged(object sender, ListChangedEventArgs e)
    {
        ProxiesDataGridView.RowCount = proxies.Count;
    }

    private void AddFromScraperToolStripMenuItem_Click(object sender, EventArgs e)
    {
        scraperForm.Show();
    }

    private void ScraperForm_SiteScraped(object sender, SiteScrapedEventArgs e)
    {
        foreach (var proxy in e.ScrapedProxies)
        {
            proxies.Add(proxy);
        }
    }
}

儿童表格

public partial class ProxyScraperForm : Form
{

    private BindingList<IProxyScraperSite> sites = new BindingList<IProxyScraperSite>();

    public int ScrapeInterval { get; set; } = 60000;

    public event EventHandler<SiteScrapedEventArgs> SiteScraped;

    public ProxyScraperForm()
    {
        InitializeComponent();

        sites.Add(new ProxyScraperSiteUsProxyOrg());
        sites.Add(new ProxyScraperSiteFreeProxyListNet());
        sites.Add(new ProxyScraperSiteFreeProxyListsNet());
        sites.Add(new ProxyScraperSiteHideMyName());
        sites.Add(new ProxyScraperSiteHidester());
        ScraperDataGridView.DataSource = sites;
    }

    private void ScrapeButton_Click(object sender, EventArgs e)
    {
        foreach (var site in sites)
        {
            Task.Run(async () =>
            {
                while (true)
                {
                    var driver = SeleniumUtility.CreateDefaultFirefoxDriver();
                    var newProxies = await site.ScrapeAsync(driver);
                    driver.Quit();
                    OnSiteScraped(newProxies);
                    await Task.Delay(5000);
                    site.Status = $"Waiting {ScrapeInterval / 1000} seconds...";
                    await Task.Delay(ScrapeInterval);
                }
            });
        }
    }

    private void OnSiteScraped(List<Proxy> scrapedProxies)
    {
        if (SiteScraped != null)
        {
            SiteScraped(this, new SiteScrapedEventArgs(scrapedProxies));
        }
    }
}

1 个答案:

答案 0 :(得分:1)

根据我们的评论,结果证明这是一个线程问题。作为一种好的做法,当代码块中可能发生异常时,请始终使用try / catch块。 :)

此外,如果您正在使用Visual Studio,则可以通过按CTRL + ALT + E并选中复选框,使VS中断更多异常。您可以阅读有关异常中断here的更多信息。