小编lor*_*tyx的帖子

foreach循环上的多线程?

我想处理一些数据.我在字典中有大约25k项.在foreach循环中,我查询数据库以获得该项目的结果.它们被添加为词典的值.

foreach (KeyValuePair<string, Type> pair in allPeople)
{
    MySqlCommand comd = new MySqlCommand("SELECT * FROM `logs` WHERE IP = '" + pair.Key + "' GROUP BY src", con);
    MySqlDataReader reader2 = comd.ExecuteReader();
    Dictionary<string, Dictionary<int, Log>> allViews = new Dictionary<string, Dictionary<int, Log>>();
    while (reader2.Read())
    {
        if (!allViews.ContainsKey(reader2.GetString("src")))
        {
            allViews.Add(reader2.GetString("src"), reader2.GetInt32("time"));
        }
    }
    reader2.Close();
    reader2.Dispose();
    allPeople[pair.Key].View = allViews;
}
Run Code Online (Sandbox Code Playgroud)

我希望能够通过多线程更快地完成这项工作.我有8个线程可用,CPU使用率约为13%.我只是不知道它是否会起作用,因为它依赖于MySQL服务器.另一方面,也许8个线程可以打开8个DB连接,因此速度更快.

无论如何,如果多线程对我的情况有帮助,怎么样?oO我从未使用(多个)线程,所以任何帮助都会很棒:D

foreach multithreading c#-4.0

4
推荐指数
1
解决办法
2858
查看次数

标签 统计

c#-4.0 ×1

foreach ×1

multithreading ×1