|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
Introduction.NET provides a fairly user friendly threading mechanism, but lacks a built-in way to easily stream large amounts of data between threads. In .NET 2.0, the The BackgroundI built this while developing an audio file transcoder, specifically to convert audio books encoded in .mp3 to .aac (or .m4b) for use on an iPod. Since .m4b was designed with the intention of retaining its location between sessions, I decided that I would like to merge my existing multi-.mp3 audio books into single .m4b files. My first attempt involved a long shell command using several pipes, but this fell through when some of the MP3 were encoded with incompatible parameters. So, I began a second attempt by wrapping the FAAC encoder in a For those unfamiliar with pipes, it is simply a means of redirecting the output of one process to the input of another in the command line without using any intermediate data storage. I like to conceptualize it using a familiar idiom - videogames!
Waka waka waka... ahem. So, the light-bike produces a series of power-cells and writes them to its standard output. These are captured and buffered inside the pipe for a waka-man to read via his standard input. The same idea applies to the
Using the codeIn general, use the
PipeStream mPipeStream; // the shared stream
public void ReadWriteMultiThreadTests()
{
mPipeStream = new PipeStream();
// create some threads to read and write data using PipeStream
Thread readThread = new Thread(new ThreadStart(ReadThread));
Thread writeThread = new Thread(new ThreadStart(WriteThread));
readThread.Start();
writeThread.Start();
writeThread.Join();
readThread.Join();
}
private void WriterThread()
{
string inputFile = File.ReadToEnd("myFile.txt");
int writeSize = 1024;
for (int i = 0; i < str.Length; i += writeSize)
{
// select a substring of characters from the input string
string substring = str.Substring(i,
(i + writeSize < str.Length) ? writeSize : str.Length - i);
sw.Write(substring.ToCharArray(), 0, substring.Length);
}
}
PipeStream in the consumer thread.private void ReaderThread()
{
char[] buffer = new char[80];
while (!sr.EndOfStream)
{
int readLength = sr.Read(buffer, 0, buffer.Length);
// do something producetive with buffer
}
}
I've extended the
The second property is valuable in scenarios when writing multiple streams to one reader - the final read will not occur until the writers are finished and this property is set to
Points of interestNote that the underlying data structure is a Related articles
History
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||