예제 #1
0
        private static async Task <byte[]> ReadAsync(CancellationToken cancellationToken)
        {
            uint readBufferLength = 1024;

            // If task cancellation was requested, comply
            cancellationToken.ThrowIfCancellationRequested();

            using (var reader = new DataReader(SerialPort.InputStream))
            {
                using (var cts = new CancellationTokenSource(5000))
                {
                    // Set InputStreamOptions to complete the asynchronous read operation
                    // when one or more bytes is available
                    reader.InputStreamOptions = InputStreamOptions.Partial;

                    uint bytesRead = 0;

                    try
                    {
                        bytesRead = await reader.LoadAsync(readBufferLength).AsTask(cts.Token);

                        await ParentPage.Emr3ConnectionConnected(true);

                        if (bytesRead > 0)
                        {
                            byte[] buffer = new byte[bytesRead];

                            reader.ReadBytes(buffer);

                            reader.DetachStream();

                            return(buffer);
                        }
                    }
                    catch (TaskCanceledException e)
                    {
                        Debug.WriteLine("Task was cancelled after timeout");
                        Debug.WriteLine(e.Message);

                        await ParentPage.Emr3ConnectionConnected(false);

                        throw;
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine("Failed LoadAsync");
                        Debug.WriteLine(e.Message);

                        throw;
                    }
                    finally
                    {
                        reader.DetachStream();
                    }
                }

                return(new byte[0]);
            }
        }