简体   繁体   中英

Visual C# very poor performance in while loop

I am having some trouble with while loops in C#. This happens let's say once per week. I am looping through a SQL Server data reader and I read simple strings, doubles etc ... I don't understand why this happens once in a while. If there were a problem in my code then its performance should be ALWAYS poor.

To be more specific, when this happens, when I set a breakpoint, the thread breaks after 3 or 4 seconds. And the weirdest thing is that if I press F5 or if I "step-by-step" the loop, it takes less time !

That's really weird and it makes me crazy.

I am wondering if someone ever encountered this type of weird deal.

Thanks in advance for your replies !

PS : The while loop is executed by a particular thread (not the main one).

PS 2 : here is my code

reader = DBConnect.GetInstance.ExecuteReader(request.ToString(), out connection, timeOut);

while (reader.Read())
{
    SourceInst sourceInst = new SourceInst();
    sourceInst.Load(reader);
    sourceInstList.Add(sourceInst);
}

Your database performance is likely varying, thus causing your issues. The SqlDataReader provides a stream to your database and does not buffer in memory. Your assumption that the "query is executed before looping" is incorrect. The stream remains open and you're reading one record at a time from the data source via cursor with this loop. Therefore, as your DB performance fluctuates, so does your loop's performance. It does not load and buffer all records into memory prior to the loop - you can do that if you like but I don't recommend it in terms of memory usage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM