Is there a way to wake a sleeping thread in C#? So, have it sleep for either a long time and wake it when you want work processed?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Expanding Wim's answer you can also specify a timeout for the
WaitHandle.WaitOne()
call. So you can use instead ofThread.Sleep()
.CancellationToken
struct provides you with one so you can signal your tasks like this:Would this thread help? C# has good functionality for thread Event handling. I've done most of my work in Python, but C# seems to have solid libraries for thread blocking.
The best solution would be to use
Task
objects with the defaultTaskFactory
. This API (introduced in .NET 4.0) uses a pool of threads with work-stealing queues and all that fancy stuff.If .NET 4.0 isn't available, then use the
ThreadPool
, which has a built-in work queue (which does some pool balancing but not on the same scope as the 4.0 thread pool).If you really must do it yourself, then I recommend a
BlockingCollection<T>
, which is a blocking consumer/producer queue added in .NET 4.0.If you really must do it yourself and can't use .NET 4.0, then you can use a
ManualResetEvent
orAutoResetEvent
along with alock
-protected queue of work.Based on Ilia's suggestion:
and...
This solution is crude, as there may be other reasons why the
ThreadInterruptedException
is thrown.There is actually a thread.Interrupt() method in C#. While the accepted answer does describes a good pattern that you probably want in your case, I came to this question looking for Thread.Interrupt so I am putting it here.
If your thread is inside a call to
Sleep
, then there isn't (usually) a way to wake it up. (The only exception I'm aware of is Java, which allows a sleep to be ended early if some other thread callsthread.interrupt()
.)The pattern that you're talking about seems to call for an event: the thread contains a loop, at the top of which it waits for an event to fire. If the event is currently unset, then the thread "sleeps" until some other thread fires the event. At that point, the sleeping thread wakes up and continues its work, until the next time through the loop when it sleeps to wait for another event.