像下面这样的代码将启动一个新线程来完成这项工作.有什么方法可以控制该线程的优先级吗?
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) 我在每个循环停止并行时遇到问题.
我正在迭代一组从表中检索到的大约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)