Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with Thread.Sleep

Tags:

c#

Is it possible that I call Thread.Sleep(1000) and the application may goto sleep for a very large amount of time like a minute or more?

It looks like that is happening in my application. I am using Thread.Sleep and the application seems to hang in the middle.

When I hit Ctrl+Alt+Break, it points to the line just before the Thread.Sleep call. If I try to watch any variable, it says the Thread is in sleep and the variable is not in scope.

EDIT:

public void Write(string command)
        {
            _port.WriteLine("\r");
            _port.WriteLine(command + "\r");
            Thread.Sleep(100);
        }
like image 451
Manoj Avatar asked Aug 03 '26 13:08

Manoj


2 Answers

The thread being in sleep doesn't necessarily mean it's literally inside Thread.Sleep; it just means that it's blocked somewhere. In this case, it's likely blocked inside your serial port write for some reason, potentially stemming from some deeper COM port issue from your topic here: C# COM port communication problem

like image 79
twon33 Avatar answered Aug 06 '26 03:08

twon33


It is possible for Thread.Sleep() to take longer than the required number of milliseconds to return, indeed quite likely, as it won't return until the time that the thread gets a CPU slice after the time has elapsed.

However, for it to take a whole minute to return is not very likely.

It could though, be the heaviest single statement in a loop that is heavy overall because it shouldn't actually be looping (or shouldn't loop as much, etc.). In this sort of situation, breaking into the debugger will most likely do so on the point where the thread sleeps (since its the heaviest single instruction, its the one most likely for breaking to find it at) so even though the real problem is this incorrect looping, it's the sleep that gets found as the "problem point" by just breaking.

It's also possible that the thread is asleep elsewhere. Since you are doing I/O I would place good money on it actually being I/O blocking that is the problem.

Try 1) checking that the I/O operation actually happens and 2) setting a breakpoint before the I/O and stepping through.

like image 43
Jon Hanna Avatar answered Aug 06 '26 03:08

Jon Hanna