我正在開發一個通過SerialPort發送和接收命令的應用程序。有時,我與之通信的硬件不響應,如何阻止我的應用程序等待響應?因爲它不允許我重試發送和接收命令。我得到一個「訪問端口'COM#'被拒絕。」當我第二次調用sendRecvCMDAsync()函數時發生異常。如何殺死(不取消)已被調用的異步任務?
這裏是我的SerialPort communicaion代碼,
public async Task<List<String>> sendRecvCMDAsync(String COMPort, String FW_CMD, List<String> SendParamList, CancellationToken ct)
{
SL_Port = new SerialPort();
try
{
if (COMPort != "")
{
SL_Port.PortName = COMPort;
}
else
{
//show a message box;
}
if (SL_Port.IsOpen)
{
SL_Port.Dispose();
SL_Port.Close();
}
SL_Port.Close();
SL_Port.Open();
SL_Port.WriteLine(FW_CMD);
_continue = true;
Array.Clear(buffer, 0, buffer.Length);
int count = 0;
while (_continue)
{
mess = "";
Task<int> bytes = SL_Port.BaseStream.ReadAsync(buffer, count, buffer.Length - count, ct);
int bytesCount = await bytes;//I need to kill this after its started, because it is not alowing me to access the COM port unless it completes.
count = bytesCount + count;
mess = Encoding.ASCII.GetString(buffer).TrimEnd('\0');
if (mess.Contains(""))
{
break;
}
else
{
}
}
}
catch (OperationCanceledException)
{
MessageBox.Show("You have Successfuly Cancelled the event");
}
catch (Exception e)
{
}
SL_Port.Dispose();
SL_Port.Close();
return listForFW;
}
我呼籲取消,但由於已經執行的代碼等待響應的這是行不通的。
這裏是我的函數調用代碼
public async void startSending()
{
cts = new CancellationTokenSource();
ReturnParams = await sendRecvCMDAsync(xport, commandSend, paramsList, cts.Token)
}
這裏是我的取消呼叫代碼。
public void btnCancelSend()
{
cts.Cancel();
}
那麼我該如何解決這個問題呢?取消不起作用。
的SerialPort沒有其方法表彰取消。因此,你不能通過這種方式取消。您可能會調用Close,但請注意,基於MSDN文檔有副作用。 –
不幸的是,關閉端口會引發異常。但我想這可以完成這項工作。 –