Click here to Skip to main content
15,910,471 members
Please Sign up or sign in to vote.
4.67/5 (3 votes)
First of all let me inform you, I am new to Threading concept.
Please note that I'm using Visual Studio 2010 (Framework : 4.0).


What I have to achieve is, create web page having three buttons and one label. and two grid to load data.

Buttons..
1. Start Thread - On Click of this button thread should start.
2. Load data in Grid 1 (Whatever operation you want but it must be server side)
3. Load data in Grid 2

Label that will display status of thread i.e. Thread started, when thread is over thread completed.


When Thread operation is going on, and If User click "Load data in Grid 1", it should load data..
If user click "Load data in grid 2", data should be loaded.

:confused:Problem what I am facing is that, until thread operation is in process.
I cant Load data in Grid.

Following code i have used for Start thread
C#
protected void btnStartThread_Click(object sender, EventArgs e)
    {
        BackgroundWorker workerLocal = new System.ComponentModel.BackgroundWorker();
        workerLocal.DoWork += new DoWorkEventHandler(DoWork);
        workerLocal.WorkerReportsProgress = false;
        workerLocal.WorkerSupportsCancellation = true;
        workerLocal.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(WorkerCompleted);

        // Calling the DoWork Method Asynchronously
        workerLocal.RunWorkerAsync();
    }

C#
private static void DoWork(object sender, DoWorkEventArgs e)
    {
        try
        {
            for (index = 0; index < 50000; index++)
            {
                // Here i am inserting record in database.
                // Just value of Index for testing purpose
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

C#
private static void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  {
      //Here i cant access LABEL to update status of thread
  }



Thanks in Advance..
Posted
Comments
Olivier Levrey 23-Feb-11 3:51am    
Just for your information: it is not necessary to put a try/catch block in your DoWork method since any exception will automatically be catched by the BackgroundWorker and sent it to the WorkerCompleted event (check out RunWorkerCompletedEventArgs to extract the exception information).
Dave Paras 23-Feb-11 5:15am    
Thanks Olivier!

In my opinion, the BackgroundWorker should be instantiated in the constructor of your class rather than doing it in a Button. All the event handlers can also be declared there in the constructor itself.

After doing the above, call the workerLocal.RunWorkerAsync(). It also takes arguments, so you can use them to pass it to the DoWork function which can recieve it using e.Argument . Then the result of the DoWork can be passed to the WorkerCompleted function .So give e.Result="Your result" in DoWork and you can recieve the result in the WorkerCompleted with e.Result.
Now it should access the Label.

Edit : Few links :

http://www.dotnetfunda.com/articles/article613-background-processes-in-asp-net-web-applications-.aspx[^]

http://www.c-sharpcorner.com/UploadFile/LivMic/BGWorker07032007000515AM/BGWorker.aspx[^]

http://www.codeproject.com/KB/web-cache/NETBackgroundWorker.aspx[^]
 
Share this answer
 
v3
Comments
Dave Paras 23-Feb-11 3:30am    
LIKE THESE ???
It will not call DoWork Method, when workerLocal.RunWorkerAsync() executes... :(

----------------------------------------------------------------
BackgroundWorker workerLocal = new System.ComponentModel.BackgroundWorker();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
workerLocal.DoWork += new DoWorkEventHandler(DoWork);
workerLocal.WorkerReportsProgress = false;
workerLocal.WorkerSupportsCancellation = true;
workerLocal.RunWorkerCompleted += new RunWorkerCompletedEventHandler(WorkerCompleted);
}
}
protected void btnStartThread_Click(object sender, EventArgs e)
{
// Calling the DoWork Method Asynchronously
workerLocal.RunWorkerAsync();
}
Tarun.K.S 23-Feb-11 3:44am    
Try instantiating the worklocal in the constructor like this : workerLocal=new BackgorundWorker();
Dave Paras 23-Feb-11 3:51am    
Do you mean constructor as page_load method?
Its web application.
I cant found constructor! :(
So if you mean of constructor by something else, please let me know where I have to initializes it?

Thanks for your time...
Tarun.K.S 23-Feb-11 3:57am    
Create a constructor with the class name. If class is ABC, then create a constructor like this:
Public ABC()
{
InitializeComponent();
//Write code here
}
Dave Paras 23-Feb-11 4:15am    
As per as my knowledge concern,
This thing can be implement in Window application..
Problem what I am facing is that, until thread operation is in process.
I cant Load data in Grid.


What's happening exactly when you click the button to load data? Is is hanging till the thread finishes? Or doesn't it do anything?

- Check that you are not accessing any UI components from the DoWork method.
- If you are accessing data base from both DoWork and UI thread, you can make the main UI thread more responsive using System.Threading.Thread.Sleep method from insice DoWork.

Unless you give more details about what you do in the thread and the button handler, I can't help further.
 
Share this answer
 
v2
Comments
Dave Paras 23-Feb-11 4:08am    
What's happening exactly when you click the button to load data? Is is hanging till the thread finishes
Same thing happen.

- Check that you are not accessing any UI components from the DoWork method.
In do work I'm just inserting record in Database. No more other then this.
Dave Paras 23-Feb-11 4:11am    
protected void LoadGrid1_Click(object sender, EventArgs e)
{
//Fetch the records by executing query
DataTable dtResult = database.FetchDataTable("Select * from TableName");

//Assign fetched result to Gridview
gv1.DataSource = dtResult;
gv1.DataBind();
}

protected void LoadGrid2_Click(object sender, EventArgs e)
{
//Fetch the records by executing query
DataTable dtResult = database.FetchDataTable("Select * from TableName");

//Assign fetched result to Gridview
gv2.DataSource = dtResult;
gv2.DataBind();
}
Olivier Levrey 23-Feb-11 4:27am    
It looks like some DataBase issue then. I am unfortunately not skilled about that. I hope somebody else will help...
Dave Paras 23-Feb-11 4:39am    
:(Hope So

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