asynchronous - C#, Async Tasks and NetworkStream.BeginRead, how to guarantee the buffer won't be overwritten? -
i'm trying write piece of code in c# read tcpclient asynchronously. here's code:
using system; using system.net; using system.net.sockets; using system.threading.tasks; class connection { private tcpclient socket; private networkstream socketstream; private byte[] buffer; private int bytesread; private task<int> readtask; public connection(tcpclient socket) { this.socket = socket; socketstream = socket.getstream(); buffer = new byte[4096]; readtask = task.factory.fromasync<byte[], int, int, int>( this.socketstream.beginread , this.socketstream.endread , this.buffer , 0 , this.buffer.length , null ); readtask.continuewith( (task) => { this.bytesread = (int)task.result; //do buffer. } , taskcontinuationoptions.onlyonrantocompletion ); } }
the problem asynchronous beginread seek write on connection object's buffer , 1 time new info arrives old 1 overwritten regardless of whether consumed or not. how should tackle problem? afaik should have closures can't figure out how!
you'd have have collection of buffers need process. allocate local buffer (var buffer = new byte[4096];
) add together buffer collection (maybe stack
) in continuation. you'll end having deal notifying thread process new info in queue.
for example:
class connection { private tcpclient socket; private networkstream socketstream; private int bytesread; private task<int> readtask; private stack<byte[]> bufferstoprocess; private readonly object lockobject = new object(); public connection(tcpclient socket) { this.socket = socket; socketstream = socket.getstream(); var buffer = new byte[4096]; readtask = task.factory.fromasync<byte[], int, int, int>( this.socketstream.beginread , this.socketstream.endread , buffer , 0 , buffer.length , null ); readtask.continuewith( (task) => { this.bytesread = (int) task.result; var actualbytes = new byte[bytesread]; array.copy(buffer, 0, actualbytes, 0, bytesread); lock (lockobject) { bufferstoprocess.push(actualbytes); } // todo: bufferstoprocess } , taskcontinuationoptions.onlyonrantocompletion ); } }
but, haven't presented plenty info tell need situation. e.g. why hasn't previous buffer been processed yet?
c# asynchronous
No comments:
Post a Comment