I have a task outputTask
. The task reads the output of a StreamReader
(with StreamReader.ReadLineAsync()
),
It only works in this way:
var outputTask = plinkInstance.StandardOutput.ReadLineAsync().ContinueWith(hasOutputReaded);
Action<Task<string>> hasOutputReaded = null;
hasOutputReaded = (previousTask) =>
{
resetTimer.Invoke();
_outputLines.Add(previousTask.Result);
previousTask = plinkInstance.StandardOutput.ReadLineAsync();
previousTask.ContinueWith(hasOutputReaded);
};
It works yes, but is there a other way to make this better?
Edit: Now it looks this way
// ...
Task.Factory.StartNew(() => readUntilEnd(plinkInstance.StandardOutput, timer, cancel.Token), cancel.Token);
// ...
And the method
private static void readUntilEnd(StreamReader stream, System.Timers.Timer timer, CancellationToken canelToken)
{
char[] buffer = new char[1];
stream.ReadAsync(buffer, 0, 1);
int cooldown = 0;
while (!canelToken.IsCancellationRequested)
{
if (buffer[0] != '\0')
{
readAChar(buffer[0]);
buffer[0] = '\0';
stream.ReadAsync(buffer, 0, 1);
timer.Stop();
timer.Start();
cooldown = 0;
}
else
{
if (cooldown < 100)
cooldown++;
}
if (cooldown > 0)
Thread.Sleep(cooldown);
}
}
Why I need the CancellationToken
? I can also pass an bool-object, or not?