Interrupt a sleeping Thread

后端 未结 7 1069
暗喜
暗喜 2020-12-13 16:08

Is there a way to Interupt a sleeping thread? If I have code similar to this.

while(true){
    if(DateTime.Now.Subtract(_lastExecuteTime).TotalHours > 1)         


        
相关标签:
7条回答
  • 2020-12-13 16:36

    why not use a BlockingCollection? I see it as a much more elegant approach than the accepted answer. i also do not think there is much overhead compared to the monitor.

    here is how to do it:

    initialize a BlockingCollection as a member:

    BlockingCollection<int> _sleeper = new BlockingCollection<int>();
    

    insted of

    Thread.Sleep(10000)
    

    do this

    int dummy;
    _sleeper.TryTake(out dummy, 10000);
    

    to wake it up you can use this code

    _sleeper.Add(0);
    
    0 讨论(0)
提交回复
热议问题