【问题标题】:use c# threadpool or task to call a function and get return value使用c#线程池或任务调用函数并获取返回值
【发布时间】:2023-03-04 08:46:01
【问题描述】:

我是 C# 线程的新手,在实现基本任务时需要帮助。 我目前正在使用下面的代码(不使用线程),它运行良好。 这个概念是循环遍历表的记录,在函数中传递一些表参数和返回值,然后用返回值更新表。

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();

我想使用线程来实现上述功能以加快处理速度,这样我就可以并行运行最多 25 个线程,而不是依次处理记录。但要求是从函数中获取返回值并在表中更新相同的值。 我已经阅读了线程池和任务(在 .net 4.0 中),但我不确定如何实现它们。请用一些示例代码指导我。

【问题讨论】:

  • 注意你的代码容易被SQL注入,查一下

标签: c# task threadpool


【解决方案1】:

有了这个答案,我的意思是你想自己创建异步实现,而不是使用现有的工具/库。

一般来说,您不能简单地从异步上下文中“返回”一个值。相反,您可以使用带有某些“返回”参数(即结果)的回调。

带有线程池的概念示例:

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);
}

【讨论】:

    【解决方案2】:

    为什么不使用异步ado.net features

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-24
      • 2010-12-18
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多