.net - Stream reading variations in C#? -
.net - Stream reading variations in C#? -
i've seen this code sample - reads stream buffer :
byte[] buffer = new byte[1024 * 32]; int bytesread; while ((bytesread = stream.read(buffer, 0, buffer.length)) > 0) { //... }
but looking @ sec parameter of stream.read(..,0,..)
zero-based byte offset in buffer @ begin storing info read current stream.
so offset 0 each time ? said doesn't overwrite info @ indexes?
on contrary : saw this example :
int read, offset = 0; while(count > 0 && (read = source.read(buffer, offset, count)) > 0) { offset += read; count -= read; }
so here offset offsetted after each reading ( seems more logical me)
but must missing :
was observation right? when should utilize each case ?
nb , pov network stream : sending file.
they're both code samples useful, in different scenario. let's pick first illustration add together code:
socket socket = ...; byte[] buffer = new byte[1024 * 32]; int bytesread; while ((bytesread = stream.read(buffer, 0, buffer.length)) > 0) { socket.beginsend(buffer, 0, bytesread , socketflags.none, null, null); // wait completion doing else? }
in case buffer
reused each time yes, info overwritten , it's intended behavior because read chunk @ time, utilize , go on.
your sec illustration pretty different: you're filling buffer
read info don't read info together, read smaller chunk each time offset
in target buffer
must increase.
how differ? in first case buffer can little want (ideally 1 byte), multiple read consume input stream. in sec case buffer must big plenty accommodate info need.
// note need know file size in advance , buffer must big plenty // accommodate info need int read, offset = 0; while(count > 0 && (read = source.read(buffer, offset, count)) > 0) { socket.beginsend(buffer, offset , read, socketflags.none, null, null); // here don't need wait beginsend() completes. offset += read; count -= read; }
which 1 better? hard say, if allocate memory in 1 shot seldom need read chunk chunk increasing offset
(only case can think performance optimization because of block size on input stream or when want - in parallel - start processing on received info while reading new ones). in contrast allocate buffer big plenty accommodate info has @ to the lowest degree 2 big drawbacks:
in general (imo) if first method (reusing same buffer) pretty in situations, performance gain may have single read (and non blocking send) is negligible in network scenario , drawbacks serious. summarize:
1 2 unknown file size yes no can run out of memory yes no parallel processing friendly no yes performance optimized no yesof course of study may "mix" both methods: 1 big circular buffer multiple smaller reads, each read advance offset pointer starting new read , in parallel processing on previous one(s). may have advantages both methods it's little bit more tricky tune (because of concurrent access , perchance overlapping read/write).
c# .net stream
Comments
Post a Comment