Is there a way to wake a sleeping thread?

后端 未结 7 1750
伪装坚强ぢ
伪装坚强ぢ 2021-01-04 05:13

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?

7条回答
  •  天涯浪人
    2021-01-04 05:35

    The best solution would be to use Task objects with the default TaskFactory. 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, 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 or AutoResetEvent along with a lock-protected queue of work.

提交回复
热议问题