时间间隔后终止线程,如果没有返回如果没有、线程、间隔、时间

2023-09-04 07:36:34 作者:另类

我有一个线程,抓住了从网络或者串口的一些数据。线程必须终止(或返回false),如果没有数据在5秒钟内收到。

I have a thread which grabs some data from network or serial port. The thread must terminate (or return false) if no data is received within 5 seconds.

在换句话说,如果运行的线程正在采取超过5秒就必须停止。

In other words, if running the thread is taking more than 5 seconds it must stop.

我写在C#中,但任何.NET语言就可以了。

I am writing in C#, but any .NET language is OK.

推荐答案

有两种方法:

线程读取从网络或串行端口的数据可以测量时间从开始的其经过的时间和等待数据为不超过剩余时间更多。网络通信API通常提供手段指定的超时的进行操作。因此,通过做一些简单的的DateTime 运算您可以在工作线程内封装超时管理。

The thread reading the data from network or serial port can measure time elapsed from its time of start and wait for the data for no more than the remaining time. Network communication APIs usually provide means to specify a timeout for the operation. Hence by doing simple DateTime arithmetic you can encapsulate timeout management within your worker thread.

使用另一个线程(或做它的主线程,如果这是可行的),等待工作线程在一定时限内完成,如果没有,则终止它。像这样的:

Use another thread (or do it in the main thread if that's feasible) to wait for the worker thread to finish within a certain time limit, and if not, abort it. Like this:

// start the worker thread
...

// give it no more than 5 seconds to execute
if (!workerThread.Join(new TimeSpan(0, 0, 5)))
{    
    workerThread.Abort();
}

建议:我会坚持的第一个解决方案,因为它会导致清洁和维护的设计。然而,在某些情况下,它可能有必要提供用于硬中止这种工作线程

Recommendation: I'd stick with the first solution, as it leads to cleaner and maintainable design. However, in certain situation it might be necessary to provide means for 'hard' abort of such worker threads.