Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

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

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.

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.

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

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# equivalent:

//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...
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...