Threading within UI form
Hi
I have a main form and a button on it - a simple user interface. Clicking the button starts a lengthy database operation. The database processing code is within the
private void button_click(object sender,EventArgs e)
{
//database operation code
}
What's the syntax for putting the database operation code into a separate thread?
many thanks
yuelin
[640 byte] By [
Yuelin] at [2007-12-18]
You’ve got two main options for this... the first is to just spawn your own local thread and have the ThreadStart function do the work for you ala:
private void button_click (object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(WorkerFunction));
thread.IsBackground = true;
thread.Start();
}
private void WorkerFunction()
{
//database operation code
}
Alternatively, (and preferred) you can use the BackgroundWorker class that is new in the 2.0 .NET Framework which allows you to define a BackgroundWorker class, create a set of EventHandlers for its events that are triggered when work has begun or is complete, and then execute the work in a background thread.
worker = new BackgroundWorker();
//Setup event handlers
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
//Begin work
worker.RunWorkerAsync();
//Called from thread different than caller when RunWorkerAsync() is called
void worker_DoWork(object sender, DoWorkEventArgs e)
{
//database operation code
}
//Called when work is complete
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine("Done!");
}
For further info on the BackgroundWorker take a look at this MSDN article.