So I want redirect my Console output to a TextBox to simulate in-GUI console. Now I saw this post:
https://stackoverflow.com/a/18727100/6871623
Which helps the redirection process.
However, since string is immutable, this means a new string will be allocated on every write and this isn't very efficient.
Therefore, I thought of using StringBuilder like:
public class ControlWriter : TextWriter
{
private Control textbox;
private StringBuilder builder;
public ControlWriter(Control textbox)
{
this.textbox = textbox;
builder = new StringBuilder();
}
public override void Write(char value)
{
builder.Append(value);
textbox.Text = builder.ToString();
}
public override void Write(string value)
{
builder.Append(value);
textbox.Text = builder.ToString();
}
public override Encoding Encoding
{
get { return Encoding.ASCII; }
}
}
Looking at the code, it doesn't seem to improve performance much since a new string will be allocated every time we call builder.ToString()
, mainly what we improve by this is the Append
portion since now we won't be using string concat every time.
Is there a way to bind TextBox Text
directly to StringBuilder
? That is, appending or resetting the StringBuilder
will automatically be reflected on GUI?
If that isn't possible for TextBox, is there another way of going around this?
Finally, is there a way to improve performance of the code above?