Would looping Thread.Sleep() be bad for performance when used to pause a thread?

ε祈祈猫儿з 提交于 2019-11-29 07:34:58
dbasnett

I think, based on the description, I'd do this

'Class level.
Private BytesWritten As Long = 0
Private NotPaused As New Threading.ManualResetEvent(True)

The change in the variable name is fitting since this is how it would be used

    'Method (thread) level.
     While BytesWritten < [target file size]
        '...write 4096 byte buffer to file...

        NotPaused.WaitOne(-1)

        '...do some more stuff...
    End While

To make the loop pause do this

    NotPaused.Reset()

and to continue

    NotPaused.Set()

In .NET there’s no reason to use Thread.Sleep besides trying to simulate lengthy operations while testing and / or debugging on an MTA thread as it will block.

Perhaps another option would be to use the TPL. Since you don't want to block you can use Task.Delay. As you probably know, a Task represents an asynchronous operation.

I think that the more elegant way is to make the thread sleep indefinitely until it's awoken by another thread calling Thread.Interrupt on the first thread that's sleeping. There's a good example of this on with example code: Pausing and Resuming Threads.

I might be misunderstanding what you're trying to achieve here, but from what I see, it seems like you're trying to block a thread until an IO task has finished. Semaphores would be the best bet here, instead of doing Thread.Sleep().

Most operating systems offer blocking semaphores that put a thread to sleep permanently until another thread wakes it up. You're probably better off utilizing them instead of constantly doing that check yourself.

Both Thread.Sleep() and blocking semaphores put the thread to sleep, but the latter does it perpetually until the resource has been freed (the semaphore has been signed). The former requires the thread to constantly wake up, check, and go back to sleep. The latter saves these execution cycles.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!