Search code examples
c#performanceclone

Slow clonig of ContextMenuStrip.Items


I have two Classes, each with their own ContextMenuStrip. As each Obejct can be accessed from the other I want to embed each ToolStripMenuItem of one object be availabe in a DropDown of the others ContextMenuStrip.

The Objects are of type MAC and TCPIP This is snippet of the MACs ContextMenuStrip:

ContextMenuStrip cms = new ContextMenuStrip();
foreach (TCPIP ip in AssignedTCPIPentries) {
    mi = new ToolStripMenuItem(ip.IP + " - " + ip.Hostname);
    for (int t = 0; t < ip.SingleItemContextMenue.Items.Count; t++) {
        mi.DropDown.Items.Add(ip.SingleItemContextMenue.Items[t]);
    }
    cms.Items.Add(mi);
}

My Problem Is that if I am working with the TCPIP onbject and am accessing the ContextMenuStrip it imidiatly opens. (as intended)

When I call the MACs ContextMenuStrip and want to embed each ContextMenuStrip.Item of each Assigned TCPIP object to a Submenu (as seen in the code above) It takes Ages (About 10 seconds per TCPIP object) to complete (each TCPIP obejct hast 21 ToolStripMenuItems). But why is it performing so bad, and how can I avoid that?

Snippet of the TCPIP.SingleItemContextMenue part:

public ContextMenuStrip SingleItemContextMenue {
            get {
                ContextMenuStrip cms = new ContextMenuStrip();
                ToolStripMenuItem mi = new ToolStripMenuItem();

                mi.Text = "IP Infos [" + IP + "]";
                mi.Click += new EventHandler(showDetailedInformation);
                mi.Image = Toolbox.Properties.Resources.Info_64;
                cms.Items.Add(mi);

                cms.Items.Add(new ToolStripSeparator()); // Horizontal line

                mi = new ToolStripMenuItem("Copy IP [" + IP + "]");
                mi.Image = Toolbox.Properties.Resources.Copy_64;
                mi.Click += new EventHandler((ss, e) => general.copyStringIntoClipboard(ss, e, IP));
                cms.Items.Add(mi);

              //And some more...
                return cms;
            }
        }

PS: foreach did not work wile Iterating through the the ContextMenuStrip.Items because of enumeration issues. But I also did not get the reason for that. But maybe it has something todo with my issue?


Solution

  • The SingleItemContextMenue getter is called on each use of ip.SingleItemContextMenue

    ContextMenuStrip cms = new ContextMenuStrip();
    foreach (TCPIP ip in AssignedTCPIPentries) {
        mi = new ToolStripMenuItem(ip.IP + " - " + ip.Hostname);
        var ipSingleItemContextMenueItems = ip.SingleItemContextMenue.Items;     // get items
    
        for (int t = 0; t < ipSingleItemContextMenueItems.Count; t++) {
            mi.DropDown.Items.Add(ipSingleItemContextMenueItems[t]);
        }
        cms.Items.Add(mi);
    }