Threading.Sleep 与 System.Threading.Tasks
如果我将 System.Threading.Thread.Sleep() 放入使用 TaskFactory.StartNew() 启动的任务中,会发生什么? 它是否使正在执行的线程本身进入睡眠状态,或者该线程是否会在第一个任务睡眠时执行另一个任务?
我问这个问题是因为我目前正在服务器上工作,有时必须等待从客户端接收数据,如果我将正在处理客户端连接的任务置于睡眠状态,我想知道该线程是否执行此特定任务然后能够在第一个连接等待数据时处理另一个连接。
what happens if i put a System.Threading.Thread.Sleep() into a Task that is started with TaskFactory.StartNew()?
Does it put the executing Thread itself to sleep or will this Thread execute another Task while the first one Sleeps?
I`m asking this because I´m currently working on a Server which must sometimes wait to receive data from its clients, and if I put the Task asleep, which is handling the client-connection, I would like to know if the Thread that executes this specific Task is then able to Handle another connection while the first one waits for data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Thread.Sleep
总是使当前执行的线程休眠,无论该线程是否正在执行任务。没有休眠任务的概念 - 只有线程。当然,线程池将允许多个线程执行,因此您最终可能会得到比实际需要更多的线程。
听起来您可能希望异步等待数据,当数据可用时继续完成任务的其余工作。
C# 5 的异步方法将使这一切变得更加简单。
Thread.Sleep
always make the currently executed thread sleep, whether that thread is executing a task or not.There's no concept of a task sleeping - only a thread. Of course the thread pool will allow multiple threads to execute, so you'll probably just end up with more threads than you really need.
It sounds like you may want to wait for the data asynchronously, continuing with the rest of the work for the task when that data is available.
C# 5's async methods will make all of this a lot simpler.