我必须在哪里抛出异常,以防止无休止等待任务

时间:2015-10-14 12:08:22

标签: c# serial-port

我有一个硬件设备通过串口连接到我的电脑上,当我向它发出信号时,它发出信号回复"嗨,我在这里!"然后成功检测到它所连接的端口。我在C#中编写了一个等待来自硬件设备的响应的任务,但是如果没有连接,那么这个任务就会永远等待。我可以在哪里抛出异常以防止这种无休止的等待?

我的代码:

public static Task<string> GetDevicePortName()
{
    // Get all available serial ports on system.
    var ports = SerialPort.GetPortNames();
    var serialPort = new SerialPort();

    serialPort.BaudRate = Constants.DeviceConstants.BaudRate;
    serialPort.Parity = Constants.DeviceConstants.SerialPortParity;
    serialPort.StopBits = Constants.DeviceConstants.SerialPortStopBits;
    serialPort.WriteTimeout = Constants.DeviceConstants.WriteTimeoutInMilliseconds;

    var taskCompletionSource = new TaskCompletionSource<string>();
    serialPort.DataReceived += (s, e) => 
    {
        var dataIn = (byte)serialPort.ReadByte();
        var receivedCharacter = Convert.ToChar(dataIn);

        if (receivedCharacter == Constants.DeviceConstants.SignalYes)
        {
            serialPort.Dispose();
            taskCompletionSource.SetResult(serialPort.PortName);
        }
    };

    foreach (var port in ports)
    {
        serialPort.PortName = port;

        try
        {
            serialPort.Open();
            serialPort.Write(Constants.DeviceConstants.SignalDeviceDetect);
        }
        catch (IOException e) { }
    }

    return taskCompletionSource.Task;
}

1 个答案:

答案 0 :(得分:2)

您可以创建一个“{1}}与Task.WhenAny

相结合的”自定义超时“
Task.Delay

请注意,此不会取消public async Task GetDevicePortNameAsync() { var cts = new CancellationTokenSource(); var timeOutTask = Task.Delay(5000, cts.Token); var deviceNameTask = GetDevicePortName(cts.Token); var finishedTask = await Task.WhenAny(timeOut, deviceNameTask); if (finishedTask == timeOutTask) { // You've timed-out } // If you get here, the deviceName is available. } 的基础注册。

修改

@KDecker添加了一个传递SerialPort的想法,如果我们在返回CancellationToken之前已经超时,则可以对其进行监控。它看起来像这样:

TaskCompletionSource.Task