Invoking Listbox in threads

11,615

Quite trivial example using it's own thread (attention just for showing, better here would maybe a BackgroundWorker!):

private Thread _Thread;

public Form1()
{
    InitializeComponent();
    _Thread = new Thread(OnThreadStart);
}

private void OnButton1Click(object sender, EventArgs e)
{
    var state = _Thread.ThreadState;

    switch (state)
    {
        case ThreadState.Unstarted:
            _Thread.Start(listBox1);
            break;
        case ThreadState.WaitSleepJoin:
        case ThreadState.Running:
            _Thread.Suspend();
            break;
        case ThreadState.Suspended:
            _Thread.Resume();
            break;
    }
}

private static void OnThreadStart(object obj)
{
    var listBox = (ListBox)obj;
    var someItems = Enumerable.Range(1, 10).Select(index => "My Item " + index).ToArray();

    foreach (var item in someItems)
    {
        listBox.Invoke(new Action(() => listBox.Items.Add(item)));
        Thread.Sleep(1000);
    }

    listBox.Invoke(new Action(() => listBox.Items.Clear()));
}
Share:
11,615
user2190928
Author by

user2190928

Updated on August 14, 2022

Comments

  • user2190928
    user2190928 over 1 year

    I am trying to have my listbox clear it self at the end of my thread. I am having issues invoking it and was hoping someone would show me how.

     public delegate void ClearDelegate(ListBox lb);
    
    
            public void ItemClear(ListBox lb)
            {
                if (lb.InvokeRequired)
                {
                    lb.Invoke(new ClearDelegate(ItemClear), new Object[] { lb });
                }
    
                listBox1.Items.Clear();
    
            }