2017-12-08 19 views
0

나는 SerialPort의 read 메소드를 기다릴 수있는 작업으로 래핑하려고합니다. 그러면 CancellationToken과 SerialPort 객체의 타임 아웃을 사용할 때 얻을 수있는 이점을 얻을 수 있습니다. 내 문제는 내가 CancellationException을 던질 수있는 작업을 얻을 수없는 것입니다. 여기 내 코드가 ...CancellationToken 및 ReadTimeout이있는 비동기 직렬 포트

static CancellationTokenSource Source = new CancellationTokenSource(); 

    static void Main(string[] args) 
    { 
     TestAsyncWrapperToken(); 
     Console.WriteLine("Press any key to cancel"); 
     Console.ReadKey(true); 
     Source.Cancel(); 
     Console.WriteLine("Source.Cancel called"); 
     Console.ReadLine(); 
    } 

    static async void TestAsyncWrapperToken() 
    { 
     try 
     { 
      using (var Port = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One)) 
      { 
       Port.Open(); 
       var Buffer = new byte[1]; 
       await Task.Factory.StartNew(() => 
       { 
        Console.WriteLine("Starting Read"); 
        Port.ReadTimeout = 5000; 
        Port.Read(Buffer, 0, Buffer.Length);       
       }, Source.Token); 
      } 
     } 
     catch (TaskCanceledException) 
     { 
      Console.WriteLine("Task Cancelled"); 
     } 
     catch (TimeoutException) 
     { 
      Console.WriteLine("Timeout on Port"); 
     } 
     catch (Exception Exc) 
     { 
      Console.WriteLine("Exception encountered {0}", Exc); 
     } 
    } 

Port.Read 메서드가 블로킹 호출이기 때문에 그렇습니까? 어떤 제안?

답변

0

두 가지 방법이 고려 될 수있다.

  1. 는 ReadAsync
    을 사용하여 그것은 SreiaPort 개체의 BaseStream property에서 Stream 개체를 얻고 Stream.ReadAsync Method (Byte[], Int32, Int32, CancellationToken)을 사용하는 것입니다.

    정확히 일치하는 내용은 아니지만 여기를 참조하십시오. 이 트리거로 DataReceivedEvent와 함께 작동하도록 DataReceivedEventSerialDataReceivedEventHandler
    변경을 사용하여
    How to cancel Stream.ReadAsync?
    NetworkStream.ReadAsync with a cancellation token never cancels

  2. .
    이 도움말의 답변을 참조하십시오.
    Sample serial port comms code using Async API in .net 4.5?

추신
.NET 4.0 이하에서 작업하려면 다음 문서를 참조하십시오.
또한 위의 관련 지식이됩니다.
If you must use .NET System.IO.Ports.SerialPort
Reading line-by-line from a serial port (or other byte-oriented stream)