Skip to main content
  1. Posts/

Implementing tail with .NET & Rx

··1 min

By default the tail command-line utility displays the last 10 lines of a file to standard output. To learn Rx, I endeavor to create a full .NET 4.0 version of tail. Here’s the initial version:

using (var stream = new FileStream (
    args[0],
    FileMode.Open,
    FileAccess.Read,
    FileShare.Read,
    2 << 15,
    true)) {
    stream.AsyncReadLines ().TakeLast (10).Run (Console.WriteLine);
}

The majority of this code is the .NET call to open the file using async I/O. The first Rx method call is AsyncReadLines() which transforms the .NET stream into an IObservable<string>. TakeLast(10) ignores all strings observed except for the last 10 lines. Run() blocks the current thread until the IObservable<T> fires OnCompleted(), and I also pass in Console.WriteLine as the argument to use for the Action<string> delegate to write the last ten lines to the console. The output of this code is identical to running tail without any parameters.

George Tsiokos
Author
George Tsiokos

Leave a comment

Preview

Comments are reviewed before publishing.