开发者

System.Threading.Thread.Sleep on Mono with Timeout.Infinite

开发者 https://www.devze.com 2023-02-20 20:00 出处:网络
I\'ve got a weird problem here. I\'m running the following C# code on Red Hat Enterprise Linux with Mono. What I\'m seeing is that the Thread.Sleep( Timeout.Infinite ); sometimes doesn\'t sleep at all

I've got a weird problem here. I'm running the following C# code on Red Hat Enterprise Linux with Mono. What I'm seeing is that the Thread.Sleep( Timeout.Infinite ); sometimes doesn't sleep at all. What I expect is that the thread blocks on the sleep, some other thread performs an Interrupt() on the sleeping thread and the "Exception caught!" line gets printed.

What I see instead is "Pre" and "Post" getting printed. (by the way, I'm maintaining someone else's code and I wouldn't have used the sleeps but I now have to live with it).

I looked online and am trying to see if there is a situation where Thread开发者_如何学Go.Sleep just won't sleep but can't find anything. Any tips are appreciated.

mj

try{
    Console.WriteLine("Pre");
    Thread.Sleep( Timeout.Infinite );
    Console.WriteLine("Post");
} catch( ThreadInterruptedException e )
{
    Console.WriteLine( "Exception caught!" );
}


Actually, this was a bug in Mono. See bug 683519.


I think the best answer would be to replace the Thread.Sleep with an AutoResetEvent, or perhaps a Semaphore. That should be a relatively clean swap, and shouldn't be a major architectural change to the existing application, like switching to the ThreadPool or something like that would be.

If that's not possible, then I'd look to see if it's possible for the sleeping thread to be aware of whether there's work for it to do. If it can have that knowledge, then set the sleep to something medium, say an hour or so, assuming that works. If the thread would happen to wake up after an hour with no work to do, it would see that there's nothing for it to do, and go back to sleep.

Also, infinite sleep not working strikes me as a fairly significant bug. Are you using the most recent version of Mono? If this is a bug which is fixed in a later version, are you able to switch to a different version?

0

精彩评论

暂无评论...
验证码 换一张
取 消