我想让我的列表框在我的帖子结束时清除它。我有问题调用它,并希望有人会告诉我如何。
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();
}
答案 0 :(得分:4)
使用它自己的主题非常简单的例子(注意仅用于显示,更好的是这里可能是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()));
}
答案 1 :(得分:0)
根据MSDN documentation
应该将listBox1.Items.Clear();
语句放入else
语句中。
另一件事是你可以使用不阻塞线程的异步方法BeginInvoke
来等待方法完成。
答案 2 :(得分:-1)
只能通过UI线程而不是工作线程访问列表框。
var sync = SynchronizatoinContext.Current;
sync.Post(delegate {
// Perform UI related changes here
}, null) //as the worker thread cannot access the UI thread resources