user34537
user34537

Reputation:

Alternative to Thead.Sleep? in C#

I have another thread polling user input. This thread is the main thread and can sleep minutes at a time. If the user hits wants to quit it may be 2+ minutes before the console window shuts down which may feel not responsive.

How can i make this thread wake up from Thread.Sleep? Do i need to use another function to sleep and pass in a bool ref for it to check when the thread wake up and end?

Upvotes: 1

Views: 442

Answers (4)

GrayWizardx
GrayWizardx

Reputation: 21141

Couple of suggestions:

  1. If your using explicit threads you can try setting ThreadType to "Background" to prevent it from blocking an exit.
  2. Try this as how you block:

main thread:

AutoResetEvent waitingEvent = new AutoResetEvent(false);
bool doneFlag = false
Thread myUIInputThread = new Thread(someFunction);

myUIInputThread.Start(waitingEvent);

while (!doneFlag) {
   doneFlag = waitingEvent.WaitOne(1000);
   if (!doneFlag) {
      Console.Writeline("Still waiting for the input thread...");
   }
}

In some function:

public void someFunction(object state) {
   Console.Write ("Enter something: ");
   Console.Readline();
   //... do your work ....

   ((AutoResetEvent)state).Set();
}
  • Not tested for exactness... YMMV :)

Upvotes: 0

Andy West
Andy West

Reputation: 12499

Have a look at the blocking queue:

http://msdn.microsoft.com/en-us/magazine/cc163427.aspx#S4

Upvotes: 1

ACP
ACP

Reputation: 35268

Use Monitor.Wait instead, and call Monitor.Pulse or Monitor.PulseAll to wake the thread up.

Upvotes: 4

Anon.
Anon.

Reputation: 59983

The solution is "Don't sleep on your UI thread". You should have a thread waiting for user input (not polling), and if you have a thread which needs to sleep (which probably isn't the case - it sounds like a hackish workaround to a different problem), then that should be separate thread that isn't handling the interface.

Upvotes: 4

Related Questions