Hi Bob,
Based on my understanding, you want to cancel the query job with a timer control. I think you have done right to use a back ground thread. According to my knowledge, I would recommend you to use BackgroundWorker along with a Timer control on the form.
Here is the sample code
public partial class Form2 : Form
{
private Timer timer;
private BackgroundWorker worker;
public Form2()
{
InitializeComponent();
worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
timer = new Timer();
timer.Interval = 15000;
timer.Tick += new EventHandler(timer_Tick);
timer.Enabled = true;
worker.WorkerSupportsCancellation = true;
worker.RunWorkerAsync();
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
timer.Enabled = false;
this.Close();
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
// Simulate the query process
while (true)
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
return;
}
}
}
void timer_Tick(object sender, EventArgs e)
{
// Write log and close
worker.CancelAsync();
worker.Dispose();
this.Close();
}
}
The Form2 is the child form which will be raised by Form1. When Form2 is created, it will start a BackgroundWork thread to do a lot of query job. The timer on Form2 will calculate the time. When it reaches 15 seconds, the work will be canceled while Form2 writing log. After that, Form2 will be forced to close.
Do I misunderstand something? Please feel free to tell me if you need any help.
Sincerely,
Kira Qian
Send us any feedback you have about the help from MSFT at fbmsdn[At]microsoft.com
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the
All-In-One Code Framework!