简体   繁体   中英

Putting a delay when using asynchronous socket methods

I am using C#, .Net Framework 3.5 for software development. My application connects to multiple clients over TCP/IP at once and collects some data from them. The client number is very high( over 100 ). Before my application development process, i have done some researches and seen that i must use asynchronous sockets implementation for the performance and manageability aspects.

It seems OK for now but i am currently searching for the best way putting a delay just before sending a data to clients. My application sometimes needs to wait around 2 seconds to send a specific data. For now, i just put a System.Threading.Thread.Sleep(2000); code line before asynchronous send method. Is this the convenient way or is there any better way to that? Does this Sleep function block my main thread of application or does it block only the thread of asynchronous socket belongs.

I would use a timer with an anonymous method instead, Thread.Sleep is (in most cases) evil...

System.Threading.Timer timer;
timer = new Timer((cs) =>
    {
        ...asynchronous send here
        timer.Dispose();
    }, null, 2000, Timeout.Inifinite);

This means that the code inside the brackets will be run once after 2000 milliseconds.

The timer.Dispose() line is very important, there is a limit to how many undisposed timers you can have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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