为什么所有任务都使用相同的cpu核心?

时间:2014-04-09 03:05:36

标签: c# multithreading multitasking

首先,我是多线程或多任务处理的新手,但我正在努力工作。我试图以两种不同的方式搜索SQL数据库:第一个搜索中点以下的ID,第二个搜索中点以上的ID。我想同时运行两个搜索;该程序有效,但当我在任务管理器中检查时,所有搜索都在一个核心上运行。

我无法弄清楚如何解决这个问题。这是我的代码;你能帮助我吗?

 public int SearchForTweetSqlID(string TweetID, string TempQuery, int MidPoint)
    {
        int ResultSmallSearch = 0;
        int ResultBigSearch = 0;

        Parallel.Invoke(() => ResultSmallSearch = TaskSearchSqlTweetID(TweetID, TempQuery, MidPoint, true).Result,
               () => ResultBigSearch = TaskSearchSqlTweetID(TweetID, TempQuery, MidPoint, false).Result
            );

        int TweetSqlID = 0;
        if (ResultSmallSearch != 0)
        {
            TweetSqlID = ResultSmallSearch;

        }
        if (ResultBigSearch != 0)
        {
            TweetSqlID = ResultBigSearch;
        }

        return TweetSqlID;
    }




     public async Task<int> TaskSearchSqlTweetID(string TweetID, string Query, int Midpoint, bool way)
    {
        SqlConnection conn = new SqlConnection(Tools.ConnectionString);
        SqlCommand comm = new SqlCommand();

        if (way == true)
        {
            comm = new SqlCommand("select * from Tweets where @VsTweetID=TweetID and ID>@VsMidPoint", conn);

        }
        else
        {
            comm = new SqlCommand("select * from Tweets where @VsTweetID=TweetID  and ID<@VsMidPoint", conn);

        }
        comm.Parameters.AddWithValue("@VsTweetID", TweetID);
        comm.Parameters.AddWithValue("@vsMidPoint", Midpoint);

        if (conn.State == ConnectionState.Closed) conn.Open();
        SqlDataReader dr = comm.ExecuteReader();

        Tweets Gidecek = new Tweets();

        if (dr.HasRows)
        {
            while (dr.Read())
            {
                Gidecek.ID = dr.GetInt32(0);

            }
            dr.Close();
            conn.Close();

            int sonuc = await Task<int>.FromResult(Gidecek.ID);

            return sonuc;

        }
        else
        {
            dr.Close();
            conn.Close();
            int sonuc = await Task<int>.FromResult(0);

            return sonuc;


        }
    }

1 个答案:

答案 0 :(得分:1)

首先,您无法从托管代码中为线程指定核心。托管代码的基本概念是所有内存,线程等任务都由VM和OS管理。

第二件事是你不会使用我看到的代码对SQL进行任何优化,因为SQL查询在SQL服务器上运行,而不是在代码中运行。

相关问题