我已经创建了4个项目来监控在线考试时间
- ASP.NET 考试申请
- 业务流程和数据访问类库
- 类库到数据库执行
- 用于监控考试时间的 Windows 窗体应用程序
在 Windows 窗体应用程序中,我在新考试开始时使用线程进行监视,我想在 5 分钟之前指示结束考试的通知。
当使用 visual studio 调试应用程序时,它没有收到任何错误。但手动单击 .exe 文件并运行应用程序时出现错误“应用程序停止工作”
这是我的windows窗体应用程序代码
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Thread t;
Thread t1;
private void Form1_Load(object sender, EventArgs e)
{
fillList();
CheckForIllegalCrossThreadCalls = false;
t= new Thread(()=>getTrigger());
t1 = new Thread(() => TimeOption());
t.Start();
t1.Start();
// getTrigger();
}
private void getTrigger()
{
int temp = StudentExamDB.getPendingCount();
while (true)
{
if (temp != StudentExamDB.getPendingCount())
{
fillList();
temp = StudentExamDB.getPendingCount();
}
}
}
List<string> added = new List<string>();
private void TimeOption()
{
while(true)
{
DataTable dt = StudentExamDB.getFinishingList();
foreach (DataRow dr in dt.Rows)
{
try
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Cells["enrollmentid"].Value.ToString() == dr["enrollmentid"].ToString())
{
if (added.Contains(dr["enrollmentid"].ToString()))
{
}
else
{
notifyIcon1.BalloonTipTitle = "Ending Some Examinations";
notifyIcon1.BalloonTipText = "click here to show more details about examination time";
notifyIcon1.ShowBalloonTip(5000);
added.Add(dr["enrollmentid"].ToString());
}
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Tomato;
dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.White;
}
}
}
catch
{
}
}
}
}
private void fillList()
{
try
{
dataGridView1.DataSource = StudentExamDB.getPendingList();
}
catch
{
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
t.Abort();
t1.Abort();
}
private void setToFinishedToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
StudentExamDB.updateStatus(int.Parse(dataGridView1.CurrentRow.Cells["enrollmentid"].Value.ToString()));
fillList();
}
catch
{
}
}
}
请您参考如下方法:
你知道这是做什么的吗?
CheckForIllegalCrossThreadCalls = false;
你明确地关闭了对你做错了什么的检查。这表明您知道您不应该在非 UI 线程上修改 UI,但您还是要这样做。如果您没有那行代码,您肯定会在 Visual Studio 中运行时遇到异常。
这至少是一个的问题。您的 TimeOption 方法在非 UI 线程上运行,但它正在修改 UI。只是不要那样做。还有各种其他选项,包括 BackgroundWorker 和 Control.Invoke/BeginInvoke。
然后...
- 您在
TimeOption和getTrigger中都有紧密的循环。基本上,您将永远用力地冲击数据库。这真是个坏主意。您应该至少在迭代之间有一个延迟 - 到处都是空的
catchblock :catch {}。这基本上是在声称无论出现什么问题,你都很好——你可以继续前进并忽略它,甚至不记录发生的事情。不要那样做。 - 您正在使用
Thread.Abort终止您的线程。不要那样做。在这种情况下,使用 volatilebool字段来指示您何时要完成并在循环的每次迭代中检查它会非常简单。
我怀疑问题是由于您从不同的线程对 UI 的不当访问造成的 - 但我不能肯定地说。修复以上所有问题,您将拥有一个更好的代码库来诊断仍然存在的任何问题。
