Ejemplo n.º 1
0
            public async Task <string> ReadError()
            {
                var q = await TaskExt.FromEvent <DataReceivedEventArgs>(
                    handler => process.ErrorDataReceived += new DataReceivedEventHandler(handler),
                    () =>
                {
                    if (!startedErrorSampling)
                    {
                        startedErrorSampling = true;
                        process.BeginErrorReadLine();
                    }
                },
                    handler => process.ErrorDataReceived -= new DataReceivedEventHandler(handler),
                    CancellationToken.None);

                return(q.Data);
            }
Ejemplo n.º 2
0
            public async Task <string> ReadOutput(TimeSpan?timeout = null)
            {
                CancellationToken cancellationToken = CancellationToken.None;

                if (timeout.HasValue)
                {
                    cancellationToken = new CancellationTokenSource(timeout.Value).Token;
                }

                var q = await TaskExt.FromEvent <DataReceivedEventArgs>(
                    handler => process.OutputDataReceived += new DataReceivedEventHandler(handler),
                    () =>
                {
                    if (!startedOutputSampling)
                    {
                        startedOutputSampling = true;
                        process.BeginOutputReadLine();
                    }
                },
                    handler => process.OutputDataReceived -= new DataReceivedEventHandler(handler),
                    cancellationToken);

                return(q.Data);
            }
    public static async Task ReadPort(SerialPort port, CancellationToken token)
    {
        while (true)
        {
            token.ThrowIfCancellationRequested();

            await TaskExt.FromEvent <SerialDataReceivedEventHandler, SerialDataReceivedEventArgs>(
                (complete, cancel, reject) => // get handler
                (sender, args) => complete(args),
                handler =>                    // subscribe
                port.DataReceived += handler,
                handler =>                    // unsubscribe
                port.DataReceived -= handler,
                (complete, cancel, reject) => // start the operation
                { if (port.BytesToRead != 0)
                  {
                      complete(null);
                  }
                },
                token);

            Console.WriteLine("Received: " + port.ReadExisting());
        }
    }