binarywriter to write binaryreader stream 100% cpu

showson1

New member
Joined
Jul 24, 2007
Messages
3
Programming Experience
1-3
Hi all.
I have some files that are binary TIF files with an ASCII header.
I wrote an app to read them, pull some values from the header, and write everything after the header as a tif.

I'm doing the reading and writing with binaryreader and binarywriter and it works, but when it goes into the loop to write out the new file it goes to 100% CPU.

Below is parts from the code dealing with writing the file, the code for the header bit is not included.

VB.NET:
        Dim fsIn As FileStream = New FileStream(filename, FileMode.OpenOrCreate)
        Dim fsOut As FileStream = New FileStream(fsIn.Name & ".tif", FileMode.Create)

        Dim binWriter As BinaryWriter
        Dim binReader As BinaryReader = New BinaryReader(fsIn)
        binWriter = New BinaryWriter(fsOut)

        Do While binReader.BaseStream.Position < binReader.BaseStream.Length
            binWriter.Write(binReader.ReadByte)
        Loop

        'Close everything out
        binWriter.Flush()
        binWriter.Close()
        binReader.Close()
        binReader = Nothing
        fsIn.Close()
        fsIn = Nothing
        fsOut.Close()
        fsOut = Nothing

Any help and / or suggestions would be very much appreciated. I'm kind of at a loss on this one.

TIA!
 
Use a BackgroundWorker, it does the work on its own thread and doesn't block UI.

The process would also benefit from reading and writing larger chunks of bytes instead of just one at a time, for example create a byte array of 100.000 items and use this as buffer.
 
Thanks for the reply.
Unfortunately using the backgroundworker did not help.. still getting 100% CPU.

I haven't tried the byte array yet, but do you (or anyone) have any other ideas?

Thanks!
 
The PC is working at its full capasity to do what you want it to do, but you don't want it to work that hard? One option is to Thread.Sleep some during the loop so the work takes longer time and allows other threads to pass, from the remarks:
Specify zero (0) to indicate that this thread should be suspended to allow other waiting threads to execute.
Another is to create a Thread to do the work asynchronous and set its ThreadPriority BelowNormal (or lower) in order for it to back off compared to normal priority threads (or higher).
 
It's not that I don't want it to work hard, it just seems like for a simple read write it shouldn't peg out the processor.
We have a similar app written in Delphi that has a very minimal impact on processor usage.

I'm not as concerned with the processor usage now anyway, your hint about the byte array sped things up enormously.

It's still pegging the processor while it's running, but it only took about 1 minutes, 17 seconds to process 850 documets. That's acceptable for our purposes.

Thanks again for the assistance!
 
Back
Top