0

I am building an application for my brother that takes string input form an external source, GPS plotter, which I would like to display in a multiline textbox. If someone were to leave this application running for an extended period I don't want the TextBox.MaxLength to be exceeded or memory allocation to become excessive.

I can't think of a good way to implement this. I need to display the last n rows in a textbox.


Edit: The marked solution is correct. Thanks Jon. I ended up making it generic. Below is what I used.

public class ArrayBuffer<T>
{
    private readonly int _maxLines;
    private int _writePosition;

    private readonly T[] _buffer;

    public ArrayBuffer(int maxLines = 100)
    {
        _maxLines = maxLines;
        _buffer = new T[_maxLines];
    }

    public T[] Push(T value)
    {
        _buffer[_writePosition++] = value;
        _writePosition %= _maxLines;
        return _buffer.Skip(_writePosition)
                             .Concat(_buffer.Take(_writePosition))
                             .Where(line => line != null).ToArray();
    }
}

Usage:

var myArrayBuffer = new ArrayBuffer<string>(50);
string[] bufferedStringArray = myArrayBuffer.Push("some string");
2
  • Maybe sober up first? Commented Jul 6, 2013 at 20:58
  • Haha. Riding the Ballmer Peak Commented Jul 6, 2013 at 21:06

1 Answer 1

4

Assuming that an acceptable solution would be to display no more than the last N lines of output each time, you could keep a circular buffer of the last N lines of input. Whenever input arrives, the oldest lines in the buffer get deleted to make room for the new arrivals.

The parts that implement the buffer:

const int MAX_LINES = 10;
int writePosition = 0;
readonly string[] buffer = new string[MAX_LINES];

When new input arrives:

// input is an IEnumerable<string>
foreach (var line in input)
{
    buffer[writePosition++] = line;
    writePosition %= MAX_LINES;
}

When you want to display output:

var linesInDisplayOrder =  buffer.Skip(writePosition)
                                 .Concat(buffer.Take(writePosition))
                                 .Where(line => line != null);
var outputText = String.Join("\n", linesInDisplayOrder);
Sign up to request clarification or add additional context in comments.

1 Comment

A tip of the hat to you good sir. That is a surpassingly cunning solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.