套接字服务器和 NUnit:Thread.Sleep [英] Socket Server and NUnit: Thread.Sleep

查看:54
本文介绍了套接字服务器和 NUnit:Thread.Sleep的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个套接字服务器和客户端类,我正在通过 NUnit 进行测试.

I am writing a socket server and client classes, which I'm testing through NUnit.

我写了一个进程,它检查所有客户端,如果它们仍然连接.对于这个过程,我创建了一个线程,但我想要的是每 5 秒运行一次这个检查.我的第一个意图是使用 Thread.Sleep().当我结束测试时,我在服务器上运行 Stop 方法,这会中断所有活动线程,这导致 Thread 从等待状态中断.

I wrote a process, which is checking all clients, if they are still connected. For this process I created a Thread, but what I want is to run this check only like every 5 seconds. My first intension was to use Thread.Sleep(). When I am ending the test, I am running the Stop method on server, which interrupt all active threads, which is causing that Thread was interruted from a waiting state.

我发现通过 Task.Delay().Wait() 有替代方法,但这导致了同样的问题.

I find out there is alternative through the Task.Delay().Wait(), but this is causing the same problem.

当我关闭服务器以结束此线程时,是否有任何其他替代 Thread.Sleep 或任何其他方式?线程正在运行 while 循环,条件为 Thread.CurrentThread.IsAlive.

Is there any other alternative to Thread.Sleep, or any other way, when I am closing server to end this thread? The thread is running while loop with condition Thread.CurrentThread.IsAlive.

推荐答案

如我在其他问题,我找到了一个更好的解决方案,因为我只想在一段时间内(比如 5 秒左右)运行检查,这里的好用法是 System.Threading.Timer类,适用于方法的周期性运行.

As answered in my other question, I found a better solution, because I want run the check only in periods of time (like 5 seconds or so), the good usage here is System.Threading.Timer class, which is suitable for the periodacal run of methods.

这篇关于套接字服务器和 NUnit:Thread.Sleep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆