1、代码
csharp
private void button2_Click(object sender, EventArgs e)
{
listBox1.Items.Add($"The thread id is {Thread.CurrentThread.ManagedThreadId}");
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler((s1, s2) =>
{
Thread.Sleep(2000);
ListBoxAcrossDomain(listBox1,$"The asynchronous thread id is {Thread.CurrentThread.ManagedThreadId}");
});
listBox1.Items.Add($"The test is start");
//注册事件来实现异步
worker.RunWorkerAsync(this);
listBox1.Items.Add($"The test is end");
}
public static void ListBoxAcrossDomain(ListBox listBox,string text)
{
if(listBox == null) return;
if(listBox.InvokeRequired)
{
listBox.Invoke(new Action(() => { listBox.Items.Add(text); }));
}
else
{
listBox.Items.Add(text);
}
}
2、运行结果