Question

First of all I am new to multithreading or multitasking but working hard on it. I'm trying to search a SQL database two different ways: the first searches IDs below the midpoint, the second searches IDs above the midpoint. I want to run both searches at the same time; the program works, but when I check in Task Manager all searches are working on one core.

I can't figure out how to fix this. Here's my code; please can you help me?

 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;


        }
    }
Was it helpful?

Solution

First of all you cannot specify core for thread from managed code. It is the very basic concept of managed code that all memory, threading and etc tasks are managed by VM and OS.

The second thing that you won't reach any optimization with SQL with the code I see, because SQL queries run at SQL-server, not in you code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top