using System; using System.IO.Ports; using System.Text; using System.Threading.Tasks; class Program { static void Main() { var portNames = SerialPort.GetPortNames(); if (portNames.Length == 0) { Console.WriteLine("シリアルポートが見つかりませんでした。"); return; } for (int i = 0; i < portNames.Length; ++i) { Console.WriteLine($"{i + 1} : {portNames[i]}"); } int portIndex; while (true) { Console.Write("ポートを選択してください >"); var s = Console.ReadLine(); if (s == null) { return; } if (Int32.TryParse(s, out portIndex) && 1 <= portIndex && portIndex <= portNames.Length) { break; } } using (var port = new SerialPort(portNames[portIndex - 1]) { BaudRate = 9600, DataBits = 8, Parity = Parity.None, StopBits = StopBits.One, Handshake = Handshake.None, NewLine = "\r", Encoding = Encoding.UTF8 }) { port.Open(); var sendTask = Task.Factory.StartNew(() => { string line; while ((line = Console.ReadLine()) != null) { port.WriteLine(line); } }); var receiveTask = Task.Factory.StartNew(() => { string line; while ((line = port.ReadLine()) != null) { Console.WriteLine(line); } }); Task.WhenAny(sendTask, receiveTask).Wait(); } } }