<p>We have a Windows Service written in C#. The service spawns a thread that does this: </p>

<pre><code>private void ThreadWorkerFunction()
{
  while(false == _stop) // stop flag set by other thread
  {
    try
    {
      openConnection();

      doStuff();

      closeConnection();
    }
    catch (Exception ex)
    {
      log.Error("Something went wrong.", ex);

      Thread.Sleep(TimeSpan.FromMinutes(10));
    }
  }
}
</code></pre>

<p>We put the Thread.Sleep in after a couple of times when the database had gone away and we came back to 3Gb logs files full of database connection errors.  </p>

<p>This has been running fine for months, but recently we've seen a few instances where the log.Error() statement logs a "System.InvalidOperationException: This SqlTransaction has completed; it is no longer usable" exception and then never ever comes back. The service can be left running for days but nothing more will be logged.</p>

<p>Having done some reading I know that Thread.Sleep is not ideal, but why would it simply never come back?</p>

[{'answer_id': 29843, 'author': 'James B', 'author_id': 2951, 'author_profile': 'https://Stackoverflow.com/users/2951', 'pm_score': 0, 'selected': False, 'text': '<p>Have you tried using <a href="http://msdn.microsoft.com/en-us/library/system.threading.monitor.pulse.aspx" rel="nofollow noreferrer">Monitor.Pulse</a> (ensure your thread is using thread management before running this) to get the thread to do something?  If that works, then you\'re going to have to look a bit more into your threading logic.</p>\n'}, {'answer_id': 29844, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n  <p>We put the Thread.Sleep in after a couple of times when the database had gone away and we came back to 3Gb logs files full of database connection errors.</p>\n</blockquote>\n\n<p>I would think a better option would be to make it so that your logging system trapped duplicates, so that it could write something like, "The previous message was repeated N times".</p>\n\n<p>Assume I\'ve written a standard note about how you should open your connection at the last possible moment and close it at the earliest opportunity, rather than spanning a potentially huge function in the way you\'ve done it (but perhaps that is an artefact of your demonstrative code and your application is actually written properly).</p>\n\n<p>When you say that it\'s reporting the error you describe, do you mean that <em>this handler</em> is reporting the error? The reason it\'s not clear to me is that in the code snippet you say "Something went wrong", but you didn\'t say that in your description; I wouldn\'t want this to be something so silly as the exception is being caught somewhere else, and the code is getting stuck somewhere other than the sleep.</p>\n'}, {'answer_id': 29920, 'author': 'Sander', 'author_id': 2928, 'author_profile': 'https://Stackoverflow.com/users/2928', 'pm_score': 4, 'selected': True, 'text': '<p>Dig in and find out? Stick a debugger on that bastard!</p>\n\n<p>I can see at least the following possibilities:</p>\n\n<ol>\n<li>the logging system hangs;</li>\n<li>the thread exited just fine but the service is still running because some other part has a logic error.</li>\n</ol>\n\n<p>And maybe, but almost certainly not, the following:</p>\n\n<ul>\n<li>Sleep() hangs.</li>\n</ul>\n\n<p>But in any case, attaching a debugger will show you whether the thread is still there and whether it really has hung.</p>\n'}, {'answer_id': 29968, 'author': 'Will Dean', 'author_id': 987, 'author_profile': 'https://Stackoverflow.com/users/987', 'pm_score': 0, 'selected': False, 'text': "<p>From the code you've posted, it's not clear that after an exception is thrown the system is definitely able to restart - e.g. if the exception comes from doStuff(), then the control flow will pass back (after the 10 minute wait) to openConnection(), without ever passing through closeConnection().</p>\n\n<p>But as others have said, just attach a debugger and find where it actually is.</p>\n"}, {'answer_id': 29979, 'author': 'Shawn', 'author_id': 26, 'author_profile': 'https://Stackoverflow.com/users/26', 'pm_score': 0, 'selected': False, 'text': '<p>Try Thread.Sleep(10 * 60 * 1000)</p>\n'}, {'answer_id': 116008, 'author': 'd4nt', 'author_id': 1039, 'author_profile': 'https://Stackoverflow.com/users/1039', 'pm_score': 0, 'selected': False, 'text': '<p>I never fully figured out what was going on, but it seemed to be related to ThreadInterruptedExceptions being thrown during the 10 minute sleep, so I changed to code to:</p>\n\n<pre><code>private void ThreadWorkerFunction()\n{\n  DateTime? timeout = null;\n\n  while (!_stop)\n  {\n    try\n    {\n      if (timeout == null || timeout &lt; DateTime.Now)\n      {\n        openDatabaseConnections();\n\n        doStuff();\n\n        closeDatabaseConnections();\n      }\n      else\n      {\n        Thread.Sleep(1000);\n      }\n    }\n    catch (ThreadInterruptedException tiex)\n    {\n      log.Error("The worker thread was interrupted... ignoring.", tiex);\n    }\n    catch (Exception ex)\n    {\n      log.Error("Something went wrong.", ex);\n\n      timeout = DateTime.Now + TimeSpan.FromMinutes(10);\n    }\n  }\n}\n</code></pre>\n\n<p>Aside from specifically catching the ThreadInterruptedException, this just feels safer as all the sleeping happens within a try block, so anything unexpected that happens will be logged. I\'ll update this answer if I ever find out more.</p>\n'}, {'answer_id': 547936, 'author': 'tkrehbiel', 'author_id': 4925, 'author_profile': 'https://Stackoverflow.com/users/4925', 'pm_score': 0, 'selected': False, 'text': "<p>Stumbled on this while looking for a Thread.Sleep problem of my own.  This may or may not be related, but if your doSomething() throws an exception, closeDatabaseConnections() won't happen, which has some potential for resource leaks.. I'd put that in a finally block.  Just something to think about.</p>\n"}, {'answer_id': 3178592, 'author': 'Michel', 'author_id': 383550, 'author_profile': 'https://Stackoverflow.com/users/383550', 'pm_score': 2, 'selected': False, 'text': "<p>I've had exactly the same problem. Moving the Sleep line outside of the exception handler fixed the problem for me, like this:</p>\n\n<pre><code>bool hadError = false;\ntry {\n  ...\n} catch (...) {\n  hadError = true;\n}\nif (hadError)\n  Thread.Sleep(...);\n</code></pre>\n\n<p>Interrupting threads does not seem to work in the context of an exception handler.</p>\n"}]
['https://Stackoverflow.com/questions/29841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1039/']