本文介绍了当用于暂停线程时,循环Thread.Sleep()会对性能造成不利影响吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多(或已经有)关于使用Thread.Sleep()方法是好是坏的讨论.据我了解,它主要用于调试目的.

There is (or there has been) a lot of talk about wether it's good or bad to use the Thread.Sleep() method. From what I understand it is mainly to be used for debugging purposes.

现在我想知道:用于我的特定目的是否不好,也就是说,不断循环以使其能够暂停/恢复线程?之所以这样做,是因为我想暂停执行I/O操作的线程,并能够以一种简单的方式恢复它.

Now I wonder: is it bad to use for my specific purpose, that is, constantly looping it to be able to pause/resume the thread? I do this because I want to pause a thread that performs I/O operations and be able to resume it in a simple way.

I/O操作基本上只是将4096字节的块写入文件,直到所有数据都写入到文件中为止.由于文件可能很大且需要很长时间,因此我希望能够暂停该操作(以防它开始占用大量系统资源).

The I/O operations are basically just writing blocks of 4096 bytes to a file until all the data has been written to it. Since the file might be large and take a long time I want to be able to pause the operation (in case it would start eating much system resources).

我的代码,VB.NET版本:

My code, VB.NET version:

'Class level.
Private BytesWritten As Long = 0
Private Pause As Boolean = False

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

    While Pause = True
        Thread.Sleep(250)
    End While

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

等效于C#:

//Class level.
long bytesWritten = 0;
bool pause = false;

//Method (thread) level.
while(bytesWritten < [target file size]) {
    ...write 4096 byte buffer to file...

    while(pause == true) {
        Thread.Sleep(250);
    }

    ...do some more stuff...
}

我听说过ResetEvents,并且对它们的用途有所了解,但是我从未真正研究过它们.

I have heard about ResetEvents and I know a little bit about what they do, but I have never really looked much into them.

推荐答案

我认为,根据描述,我会这样做

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

并继续

    NotPaused.Set()

这篇关于当用于暂停线程时,循环Thread.Sleep()会对性能造成不利影响吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 23:19