Click here to Skip to main content
15,916,215 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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..
Posted

1 solution

A background worker is a separate thread from the one that runs the user interface - what that means is that the processor will run it independently (and indeed may run it on a different core if you have more than one). It's a bit like having someone working for you: you can give them a task, and tell them to get on with it, and you don't have to think about it until they have finished.

Simplest code for a separate thread:

C#
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++);
        }
    }
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.
 
Share this answer
 
Comments
d_lucifer 3-Sep-11 6:57am    
Thank you very much for your solution.but in my case, user doesn't interact any time with that method.so the background worker should be started automatically.do you have any idea about that?
OriginalGriff 3-Sep-11 6:59am    
Mine was just an example - you could move the code to your Form Load event? Or your Class constructor? Whatever fits your application best...
d_lucifer 3-Sep-11 10:16am    
yeah, i'll try. thanks for the help... :) :)
OriginalGriff 3-Sep-11 12:11pm    
You're welcome

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900