相关疑难解决方法(0)

降低Task.Factory.StartNew线程的优先级

像下面这样的代码将启动一个新线程来完成这项工作.有什么方法可以控制该线程的优先级吗?

Task.Factory.StartNew(() => {
    // everything here will be executed in a new thread.
    // I want to set the priority of this thread to BelowNormal
});
Run Code Online (Sandbox Code Playgroud)

.net c# multithreading .net-4.0 taskfactory

35
推荐指数
4
解决办法
4万
查看次数

立即停止Parallel.ForEach

我在每个循环停止并行时遇到问题.

我正在迭代一组从表中检索到的大约40.000个DataRows,当我在结果集中有100个项目时,我需要立即停止循环.问题是当我在ParallelLoopState上触发Stop方法时,迭代不会立即停止,导致我的结果集不一致(无论是少数项还是多项).

有没有办法确定,一旦我停止,我就会杀死所有线程?

  List<DataRow> rows = new List<DataRow>(dataTable.Select());
  ConcurrentDictionary<string, object> resultSet = new ConcurrentDictionary<string, object>();

  rows.EachParallel(delegate (DataRow row, ParallelLoopState state)
  {
    if (!state.IsStopped)
    {
      using (SqlConnection sqlConnection = new SqlConnection(Global.ConnStr))
      {
        sqlConnection.Open();

        //{
        // Do some processing.......
        //}       

        var sourceKey = "key retrieved from processing";
        if (!resultSet.ContainsKey(sourceKey))
        {
          object myCustomObj = new object();

          resultSet.AddOrUpdate(
          sourceKey,
          myCustomObj,
          (key, oldValue) => myCustomObj);
        }

        if (resultSet.Values.Count == 100)
          state.Stop();
      }
    }
  });
Run Code Online (Sandbox Code Playgroud)

.net c# multithreading parallel.foreach

2
推荐指数
1
解决办法
660
查看次数