vishal gupta

vishal gupta

  • 1.5k
  • 92
  • 2.9k

use c# threadpool or task to call a function and get return value

Oct 10 2012 8:15 AM
I am a newbie to c# threads and need help in implementing a basic task.
I am using below code currently (without using thread) which runs fine. 
The concept is to loop through records of a table, pass some table arguments in a function and except a return value and then update the table with the return value.

    cmd = new OleDbCommand { Connection = con, CommandText = "Select recid,col_A,col_B from tblData"};
    dr = cmd.ExecuteReader();
    
    if (dr.HasRows)
    {
       cmdRec = new OleDbCommand { Connection = con };
       while (dr.Read())
        {
    sReqResult = DoProcessing(dr["col_A"].ToString(), dr["col_B"].ToString(), dr["PARAM2"].ToString());
            sSql = "update tblData set STATUS='" + sReqResult + "' where recid = '" + dr["recid"] + "'";
    cmdRec.CommandText = sSql;
    cmdRec.ExecuteNonQuery(); 
        }
    }
    dr.close();

I want to implement above functionality using threads to speed up the process so that instead of processing the records sequentely, I can run a maximum of 25 threads parallelly. but requirement is to get the return value from the function and update the same in the table.
I have read about threadpool and Tasks (in .net 4.0) but I am not sure how to implement the same. Please guide me with some sample code.

Answers (1)