Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking Listbox in threads

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();

        }
like image 375
user2190928 Avatar asked Jan 21 '26 13:01

user2190928


1 Answers

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()));
}
like image 93
Oliver Avatar answered Jan 24 '26 10:01

Oliver