不要在线程已在运行时执行线程
本文关键字:线程 执行 运行时 | 更新日期: 2023-09-27 17:56:51
我有一个线程可以将日期导出到Excel中。
但是当我第二次运行线程时,它可能无法执行。
我的代码:
if (Thread.CurrentThread == null || Thread.CurrentThread.ThreadState == System.Threading.ThreadState.Stopped)
{
new Thread(() =>
{
Thread.CurrentThread.Name = "Export to Excel Thread";
Thread.CurrentThread.IsBackground = true;
//Code to export to Excel
// ...
}).Start();
}
else
{
MessageBox.Show("Please wait untill the current export is done");
}
我认为问题是线程不是 if 语句中的当前线程。
如何解决这个问题?
我会选择TPL。
你可以使用这样的东西:
// in your class
private Task _exportTask;
// in your method
if(_exportTask == null || _exportTask.IsCompleted || _exportTask.IsCanceled || _exportTask.IsFaulted)
{
_exportTask = Task.Factory.StartNew(() => /* Code to export to Excel */);
}
else
{
MessageBox.Show("Please wait until the current export is done");
}
解释为什么你的代码不起作用:
当前线程永远不能null
,因为这意味着没有线程来执行执行此检查的代码。同样,它不能停止,因为这再次意味着你的检查代码不会被执行,因为线程被停止了。
Thread.CurrentThread
始终返回正在执行访问 Thread.CurrentThread
值的代码的线程。
我认为你应该使用BackgroundWorker class来为你处理线程的东西。在第二个导出按钮上,单击只需选中 IsBusy 属性,如果为真,则不执行任何操作。祝你好运。
当第一个线程正在运行(创建 Excel)时,线程可能不会再次执行。直到线程完成并再次单击"导出"按钮!
这可以通过禁用按钮非常简单地完成。
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
Task.Run(() =>
{
// ... do something here
Invoke((Action)(() => button1.Enabled = true)); // enable button again
});
}
如果可以从多个位置(按钮、菜单、自动化、调度程序等)调用导出,请查看其他答案。