简体   繁体   English

一段时间后调用方法而不会阻塞

[英]Call a method after a certain period of time without blocking

I'm making a webserver application, and I have a Listener class which waits for connections and spawns an HTTPConnection , passing it the new Socket created, each time a connect request is made. 我正在制作一个Web服务器应用程序,并且有一个Listener类,它等待连接并生成HTTPConnection ,每次发出连接请求时,将创建的新Socket传递给它。 The HTTPConnection class waits for data asynchronously (using Socket.BeginReceive ). HTTPConnection类异步等待数据(使用Socket.BeginReceive )。

I need the delayed execution for a timeout. 我需要延迟执行以超时。 If the client fails to send a full HTTP request after a certain amount of time, I want to close the connection. 如果客户端在一定时间后未能发送完整的HTTP请求,我想关闭连接。 As soon as the HTTPConnection object is constructed, the waiting period should begin, then call a Timeout function if the client fails to send the request. 一旦构造了HTTPConnection对象,等待期就应该开始,如果客户端发送请求失败,则调用Timeout函数。 Obviously, I can't have the constructor method paused for a few seconds, so the waiting needs to happen async. 显然,我不能将构造方法暂停几秒钟,因此等待需要异步进行。 I also need to be able to cancel the task. 我还需要能够取消任务。

I could do new Thread(...) and all, but that's very poor design. 我可以做new Thread(...)等等,但这是非常糟糕的设计。 Are there any other ways to schedule a method to be called later? 还有其他方法可以安排以后要调用的方法吗?

You could append all postponed events to some ordered data structure and have a background task checking at certain interval if there's a timeout event that have to be executed. 您可以将所有延迟的事件追加到某个有序的数据结构中,并在一定间隔下进行后台任务检查(如果必须执行超时事件)。

You could save these events in database also (if you have a lot of clients I imagine it could lead to high memory usage). 您也可以将这些事件保存在数据库中(如果您有很多客户端,我想这可能会导致大量内存使用)。

Also you background task could get all the expired events from the database and handle them at once. 您的后台任务也可以从数据库中获取所有过期的事件并立即处理它们。

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

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