Interrupt a sleeping Thread

后端 未结 7 1136
暗喜
暗喜 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 _sleeper = new BlockingCollection();
    

    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);
    

提交回复
热议问题