3

我试图让我的列表框在我的线程结束时自行清除。我在调用它时遇到问题,希望有人能告诉我如何。

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

        }
4

3 回答 3

5

使用它自己的线程的相当简单的例子(注意只是为了展示,这里可能会更好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()));
}
于 2013-07-10T10:59:05.717 回答
0

根据MSDN 文档listBox1.Items.Clear();,将语句放入语句 中就足够了else

另一件事是您可以使用BeginInvoke不阻塞线程等待方法完成的异步方法。

于 2015-12-10T12:23:30.387 回答
-1

Listbox 只能被 UI 线程访问,不能被工作线程访问。

    var sync = SynchronizatoinContext.Current;

    sync.Post(delegate {
     // Perform UI related changes here
}, null) //as the worker thread cannot access the UI thread resources
于 2013-07-10T10:01:33.300 回答