简体   繁体   English

线程vs计时器vs服务

[英]Threads vs Timer vs Service

I was reading this blog Easy Background Tasks about the badge system of some page called stackoverflow :P, so, in a comment says that they ended with a service that perform the task, but for example: 我正在阅读此博客Easy Background Tasks,该博客的内容与某些页面的badge系统有关,该页面称为stackoverflow:P,因此,在一条评论中说,它们以执行任务的服务结尾,但是例如:

User performs action in time T1 This action depends of X number of users After time T2, you need to execute some db query and notify user(email or whatever) 用户在时间T1中执行操作此操作取决于X个用户。在时间T2之后,您需要执行一些数据库查询并通知用户(电子邮件或其他内容)

I say this because of the real time experience, so the question here is, if you use threads, lets say you have 1000 users that perform actions, you will have 1000 waiting threads, so in some time, there will be reciclyng, or if the server shutsdown for some reason, you will lose all this tasks. 我说这是出于实时经验,所以这里的问题是,如果您使用线程,可以说您有1000个执行操作的用户,那么您将有1000个等待线程,因此在某些时候会有recilyng,或者服务器由于某种原因而关闭,您将丢失所有这些任务。 Using a timer will end in the same situation 使用计时器将在相同情况下结束

If you use a service you will lose the real time experience, for example in an online game. 如果使用服务,您将失去实时体验,例如在在线游戏中。

So, how to deal with this kind of stuff? 那么,如何处理这种东西呢?

You should be careful when using threads and signaling. 使用线程和信令时应小心。 The solution depends to the details of the scenario, but one of the scalable solutions is polling . 解决方案取决于场景的详细信息,但是可伸缩解决方案之一是polling

Based on your scenario, signaling between threads is not efficient as there's always a limited number of available threads in the threadpool. 根据您的方案,线程之间的信号传输效率不高,因为线程池中始终有数量有限的可用线程。 However, if you know the maximum number of users who will hold a thread ( depending on the game design ) , you can use signaling using WaitHandles ( AutoResetEvent and/or ManualResetEvent) to signal between threads. 但是,如果您知道拥有线程的最大用户数量(取决于游戏设计),则可以使用通过WaitHandles(AutoResetEvent和/或ManualResetEvent)发出的信号在线程之间发出信号。 But make sure that you have increased the number of available threads in the pool in the Application_Start event handler of the Global.asax 但是,请确保在Global.asax的Application_Start事件处理程序中增加了池中可用线程的数量。

            int availableThreads;

            int availablePorts;

            ThreadPool.GetAvailableThreads(out availableThreads, out availablePorts);

            ThreadPool.SetMinThreads(availableThreads, availablePorts);

Hope it helps. 希望能帮助到你。

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

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