Книга: C# 2008 Programmer

BufferedStream

BufferedStream

To improve its performance, the BufferedStream class works with another Stream object. For instance, the previous example used a buffer size of 8192 bytes when reading from a text file. However, that size might not be the ideal size to yield the optimum performance from your computer. You can use the BufferedStream class to let the operating system determine the optimum buffer size for you. While you can still specify the buffer size to fill up your buffer when reading data, your buffer will now be filled by the BufferedStream class instead of directly from the stream (which in the example is from a file). The BufferedStream class fills up its internal memory store in the size that it determines is the most efficient. 

The BufferedStream class is ideal when you are manipulating large streams. The following shows how the previous example can be speeded up using the BufferedStream class:

try {
 const int BUFFER_SIZE = 8192;
 byte[] buffer = new byte[BUFFER_SIZE];
 int bytesRead;
 string filePath = @"C:tempVS2008Pro.png";
 string filePath_backup = @"C:tempVS2008Pro_bak.png";
 Stream s_in = File.OpenRead(filePath);
 Stream s_out = File.OpenWrite(filePath_backup);
 BufferedStream bs_in = new BufferedStream(s_in);
 BufferedStream bs_out = new BufferedStream(s_out);
 while ((bytesRead = bs_in.Read(buffer, 0, BUFFER_SIZE)) > 0) {
  bs_out.Write(buffer, 0, bytesRead);
 }
 bs_out.Flush();
 bs_in.Close();
 bs_out.Close();
} catch (Exception ex) {
 Console.WriteLine(ex.ToString());
}

You use a BufferedStream object over a Stream object, and all the reading and writing is then done via the BufferedStream objects.

Оглавление книги

Оглавление статьи/книги

Генерация: 3.800. Запросов К БД/Cache: 3 / 1
поделиться
Вверх Вниз