问题描述
我想在表单中添加一个方法,该方法会不时检查数据库表,并将最新记录保存到网格视图中.实际上,我知道如何执行此方法的SQL查询部分.
但是,问题是我对如何将此方法作为一个单独的进程运行一无所知.我从Google那里得到了一个叫做后台工作者"和线程"的东西.但是我不熟悉那些概念.
因此,伙计们,我需要您的帮助,才能至少在某种程度上完成此工作.
谢谢..
I want to add a method to my form, which checks a table of my database time to time and get the most-recent record on to the grid view. Actually I know how to do the SQL query part of this method.
However, the thing is I don''t have any idea on how to run this method as a separate process. I got somethings called "Background workers" and "threads" from Google. But I''m not familiar with those concepts.
So guys I need your help to get this thing done at least for some point.
Thanks..
推荐答案
private bool run = false;
BackgroundWorker bgw = new BackgroundWorker();
private void myButton_Click(object sender, EventArgs e)
{
if (!run)
{
run = true;
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.RunWorkerAsync();
}
else
{
run = false;
}
}
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
int i = 0;
while (run)
{
Thread.Sleep(1000);
Console.WriteLine("Hello : " + i++);
}
}
单击按钮可设置一个工作程序,告诉它要执行的操作,运行它并开除程序.再次按下该键时,它会自然终止,从而终止线程.
在您的情况下,数据库访问代码将位于bgw_DoWork方法中,并且如果需要,可以通过ProgressChanged事件报告进度.
顺便说一句:不要直接模仿这个:多次按下按钮会导致问题,因为每个线程都会启动一个新线程-这只是一个简单的示例.
The button click sets up a worker, tells it what to do, runs it and buggers off. When you press it again, it kills the thread, by letting it expire naturally.
In your case, the database access code would be in the bgw_DoWork method, and it could report progress if needed via the ProgressChanged Event.
BTW: Don''t emulate this directly: multiple presses of the button would cause problems as a new thread would start for each - this is just a simple example.
这篇关于使用C#&的数据库检查器微软SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!