通过超时取消TcpClient ReadAsync操作并在.NET 4.5中捕获此超时事件的正确方法是什么?
TcpClient.ReadTimeout似乎应用于同步只读.
更新:
Tried tro应用此处描述的方法取消异步操作
var buffer = new byte[4096];
CancellationTokenSource cts = new CancellationTokenSource(5000);
int amountRead = await tcpClientStream.ReadAsync(buffer, 0, 4096, cts.Token);
Run Code Online (Sandbox Code Playgroud)
但它永远不会超时取消.有什么问题吗?
我2的设备类型具有不同的协议并与单个串行端口连接。通过协议,我的意思是串口配置不同。
我有一个协议 ID p_id,我可以通过它检查当前正在读取哪个设备。下面是我的代码
下面是我的主函数,它调用一个名为的类 CombinedEngine
static class Program
{
private static CombinedEngine _eng;
static async Task Main(string[] args)
{
try
{
_eng = new CombinedEngine();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message.ToString());
//_log.Error(ex, ex.Message);
}
}
while(true);
}
Run Code Online (Sandbox Code Playgroud)
组合发动机类
class CombinedEngine
{
SerialPort port = new SerialPort();
public CombinedEngine()
{
try
{
var p = mdc.mdc_protocol.ToList();
if(p.Count > 0)
{
foreach(var pr in p)
{
var p_id = pr.protocol_id;
if(p_id=="01")//modbus
{
if (port.IsOpen)
port.Close();
port = new …Run Code Online (Sandbox Code Playgroud)