One stream, two threads...

  • Thread starter Thread starter Nathan Baulch
  • Start date Start date
N

Nathan Baulch

I have a single stream that I need two threads to independently move
through.
How can I achieve this without duplicating the stream data in memory?
Obviously I can't simply give both threads references to the same stream as
they will share the stream's position pointer.

For a demonstration of my problem, throw three multiline textboxes and a
button onto the form and paste this code in:


private void button1_Click(object sender, System.EventArgs e) {
StringReader reader = new StringReader(textBox1.Text);
ThreadPool.QueueUserWorkItem(new WaitCallback(one),reader);
ThreadPool.QueueUserWorkItem(new WaitCallback(two),reader);
}

private void one(object Sender) {
textBox2.Text += ((StringReader)Sender).ReadLine();
}

private void two(object Sender) {
textBox3.Text += ((StringReader)Sender).ReadLine();
}


Put a few lines of text into textBox1 and click the button.

Nathan
 
Hello Nathan.

Use two readers pointing to the same string/stream, such as:

TextReader reader = new StringReader(textBox1.Text));
TextReader reader2 = new StringReader(textBox1.Text));
ThreadPool.QueueUserWorkItem(new WaitCallback(two),reader);
ThreadPool.QueueUserWorkItem(new WaitCallback(one),reader2);

Hope this helps.
 
Back
Top