Repository navigation
Expand file tree
/
Copy pathConsoleProxy.cs
More file actions
89 lines (70 loc) · 2.29 KB
/
Copy pathConsoleProxy.cs
File metadata and controls
89 lines (70 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.IO;
using System.IO.Pipes;
using System.Text;
using System.Threading.Tasks;
using ICSharpCore.Primitives;
namespace ICSharpCore.Script
{
public class ConsoleProxy : IDisposable
{
private TextWriter _originalOut = Console.Out;
private AnonymousPipeServerStream _consoleOutPipe;
private Action<string> _consoleHandler;
private StreamWriter _consoleWriter;
private Task _readTask;
public ConsoleProxy(Action<string> consoleHandler)
{
_consoleOutPipe = new AnonymousPipeServerStream(PipeDirection.Out);
_consoleWriter = new StreamWriter(_consoleOutPipe);
_consoleWriter.AutoFlush = true;
_consoleHandler = consoleHandler;
Console.SetOut(_consoleWriter);
}
public void StartRedirect()
{
_readTask = ReadLineAsync();
}
private async Task ReadLineAsync()
{
using (var consoleOutClientPipe = new AnonymousPipeClientStream(PipeDirection.In, _consoleOutPipe.ClientSafePipeHandle))
using (var reader = new StreamReader(consoleOutClientPipe))
{
while (true)
{
var line = await reader.ReadLineAsync().ConfigureAwait(false);
if (line != null)
OnLineReceived(line);
if (line == null || reader.EndOfStream)
break;
}
}
}
private void OnLineReceived(string line)
{
_consoleHandler(line);
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
_consoleWriter?.Flush();
_consoleWriter?.Dispose();
}
Console.SetOut(_originalOut);
_readTask?.Wait();
_readTask = null;
disposedValue = true;
}
}
void IDisposable.Dispose()
{
Dispose(true);
}
#endregion
}
}