user1734642
user1734642

Reputation: 77

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

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.

Upvotes: 1

Views: 5356

Answers (2)

Patrik Westerlund
Patrik Westerlund

Reputation: 464

With this answer, I'm implying you want to create the async-implementation yourself, and not use an existing tool/library.

In general, you wont be able to simply "return" a value from an asynchronous context. Instead, you can have a callback that takes certain "return"-parameters (i.e. the result).

Concept example with threadpool:

if (dr.HasRows)
{
    object someDataToWorkWith = "data";

    Action<object> resultCallback = (theResults) =>
    {
        // Executed once the workItem is finished.
        // Work with and/or present the results here.
    };

    WaitCallback workItem = (dataOrSomeDetails) =>
    {
        // This is the main async-part. Work with or fetch data here.
        // You can also access any variables from the containing method.
        // When finished working, execute callback:
        resultCallback("someResults");
    };

    ThreadPool.QueueUserWorkItem(workItem, someDataToWorkWith);
}

Upvotes: 1

Sanja Melnichuk
Sanja Melnichuk

Reputation: 3505

Why not use asynchronous ado.net features?

Upvotes: 0

Related Questions