views:

650

answers:

1

Hi all,

I'm having a problem updating a control on my ui from a thread created using

ThreadPool.QueueUserWorkItem

Inside this thread i am calling

addControlToPanel(li);

As shown here

private delegate void addControlToPanelDelegate(ListItem li);
private void addControlToPanel(ListItem li)
{
    if (panel1.InvokeRequired)
    {
        addControlToPanelDelegate d = new addControlToPanelDelegate(addControlToPanel);
        panel1.Invoke(d, new object[] { li });
    }
    else
    {
        panel1.Controls.Add(li);
    }
}

On first entry to addControlToPanel() panel1.InvokeRequired == true so a delegate is instantiated and then invoked, now on this entry into addControlToPanel(), panel1.InvokeRequired == false so I add the control to the panel.

My problem is that even after invoking against the control and panel1.InvokeRequired being false I get an error on the

panel1.Controls.Add(li);

line stating the usual

Control.Invoke must be used to interact with controls created on a separate thread.

Can anybody spot the problem? Using invoke to access controls on another thread is something i have done many times before but this one has me stumped!

TIA

OneSHOT

A: 

It seems the problem was passing a control on the invoke (ListItem is a form control that i have created) instead i refactored the code so that rather than creating the control and passing it into the

addControlToPanel()

method, i pass all the info needed to create the control inside the method after invoking as so

private delegate void addControlToPanelDelegate(string picname, string thumburl, PicasaEntry entry, Int32 top, EventHandler clickevent);
private void addControlToPanel(string picname, string thumburl, PicasaEntry entry, Int32 Ordinal,EventHandler clickevent)
{
    if (panel1.InvokeRequired)
    {
        addControlToPanelDelegate d = new addControlToPanelDelegate(addControlToPanel);
        this.Invoke(d, new object[] { picname, thumburl, entry, Ordinal, clickevent });
        //panel1.Invoke(d, new object[] { li });
    }
    else
    {
        ListItem li = new ListItem(picname, thumburl, entry);
        li.Top = Ordinal * li.Height;
        li.Click += clickevent;
        panel1.Controls.Add( li);
    }
}

Cheers

OneSHOT

OneSHOT