简体   繁体   English

未捕获C#超时异常

[英]C# timeout exception not caught

I'm reading some data over TCP/IP and for some reason timeout exception is not caught. 我正在通过TCP / IP读取一些数据,由于某种原因未捕获到超时异常。 Any ideas what's wrong here? 有什么主意吗?

try
{
    Timer timer1 = new Timer(dcaika);
    timer1.Elapsed += async (sender, e) => await HandleTimer();
    timer1.Start();
    memoryRes = dc.readBytes(libnodave.daveFlags, 0, 180, 1, memoryBuffer);
    timer1.Stop();
}
catch (TimeoutException)
{
}

and here is timeout handling 这是超时处理

private static Task HandleTimer()
{
    Console.WriteLine("timeout");
    throw new TimeoutException();
}

That's just not the way .NET events work. 但这不是.NET事件的工作方式。 They don't interrupt a thread; 他们不中断线程。 they'll be run in a context determined by the type of timer it is. 它们将在由计时器类型决定的上下文中运行。 In this case ( System.Timers.Timer ), the Timer.Elapsed event handler will be invoked on a thread pool thread. 在这种情况下( System.Timers.Timer ), Timer.Elapsed事件处理程序将在线程池线程上调用。 So, it's running on a completely different thread than the try / catch , and that's why it won't work. 因此,它在与try / catch完全不同的线程上运行,这就是为什么它不起作用的原因。

It looks like you're trying to force a timeout on an API that doesn't natively support timeouts. 看来您要在本机不支持超时的API上强制超时。 There's no clean way to do this. 没有干净的方法可以做到这一点。 So, the first thing to do is to ask whoever maintains readBytes for timeout support. 因此,要做的第一件事是询问谁维护readBytes以获得超时支持。

There is a way to do "fake timeouts" like this: 一种方法做“假超时”是这样的:

var timeoutTask = Task.Delay(dcaika);
var readTask = Task.Run(() => dc.readBytes(libnodave.daveFlags, 0, 180, 1, memoryBuffer));
var completedTask = await Task.WhenAny(timeoutTask, readTask);
if (completedTask == timeoutTask)
  ...
else
  ...

But this approach will not stop the readBytes call , so it will probably continue reading bytes and mess up your other communications. 但是这种方法不会停止readBytes调用 ,因此它可能会继续读取字节并弄乱您的其他通信。 So I don't think it will work for your scenario. 因此,我认为这不适用于您的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM