Windows Service定期产生最大线程数 [英] Windows Service to regularly spawn a thread up to a maximum

查看:81
本文介绍了Windows Service定期产生最大线程数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我已经阅读了数百页并使用了如此多的样本,以至于我完全感到困惑.大多数示例似乎都针对以下目标:

I have read hundreds of pages and employed so many samples by now that I am completely confused. Most examples seems to target the following:

  • 有一个计时器会产生一个新的线程,该线程可以无限执行 线程
  • 产生一定数量的线程,每个线程都有一个计时器 东西
  • 定期做一些工作
  • Have a timer spawn a new thread that will do some work, with infinite threads
  • Spawn a specific number of threads, each with a timer that does something
  • On a regular basis do some work

我想要完成的是:

  • 运行计时器以定期生成线程
  • 此线程可能花费或可能不会超过计时器标记
  • 对可以产生多少个线程有限制
  • 线程完成后,将线程放回,以便可以再次使用
  • 每个线程中的工作彼此独立,并且可以异步运行(这没关系)

以此类推,我希望我的应用程序像具有10条钓鱼线的渔船一样工作.在开始时,您逐一淘汰(按需),然后逐一淘汰,依此类推.在任何给定时间,水中可能会有0到10条钓鱼线.每当钓到一条鱼时,钓线就会被拉起并准备再次放鱼(如果有需求的话).

As an analogy, I want my application to work like a fishing boat with 10 fishing lines. At the start you cast one out (on demand), then another and so on. At any given time there can be from 0 to 10 fishing lines in the water. Whenever a fish is caught the line gets pulled up and is ready to be cast again (if there is the demand to).

听起来我应该使用ThreadPool?我还认为,为简单起见,我应该生成一个线程,如果没有工作,请立即返回它(即从某个表中选择count,如果count为0,则返回线程),而不是试图聪明地找出来.如果我因为需要而需要产卵.

It sounds like I should be using a ThreadPool? I was also think that to keep it simple I should spawn a thread, and if there is no work, return it immediately (i.e. select count from some table and if count is 0, return the thread), instead of trying to intelligently figure out if I need to spawn because there is a need.

通常,当系统处于安静状态时,它将不断产生一个线程,看到没有任何工作,然后返回,但是在繁忙的时候,这些线程可能会用尽极限,从而系统将继续产生新线程失败,直到完成后再次返回一个或多个线程.

In general, when the system is quiet, it will constantly be spawning one thread, see that there's no work and then return, but during busy times, the threads will probably be used up to the limit, whereby the system will just keep on failing to spawn new threads until one or more is returned again when they're finished.

我已经尝试了System.Threading和Semaphores和WaitHandles,但是这一切都令人困惑.我没有要显示的代码,因为我继续使用另一种方法删除并重新开始.任何帮助将不胜感激.

I have tried System.Threading and Semaphores and WaitHandles but it all gets terribly confusing. I have no code to show yet, as I keep on deleting and starting again, with a different approach. Any help would be appreciated.

我在C#2010中进行开发.

I develop in C# 2010.

推荐答案

在使用线程池和计时器之前,我已经完成了类似的工作:

I've gotten something like this working before using the threadpool and a timer:

public class MaxThreadCountWorker : IDisposable
{
    private readonly int _maxThreadCount;
    private readonly int _tickIntervalMilliseconds;
    private readonly Action _periodicWork;
    private readonly System.Threading.Timer _timer;
    private int _currentActiveCount;

    public MaxThreadCountWorker(int maxThreadCount, int tickIntervalMilliseconds, Action periodicWork)
    {
        _maxThreadCount = maxThreadCount;
        _tickIntervalMilliseconds = tickIntervalMilliseconds;
        _periodicWork = periodicWork;
        _timer = new System.Threading.Timer(_ => OnTick(), null, Timeout.Infinite, Timeout.Infinite);
        _currentActiveCount = 0;
    }

    public void Start()
    {
        _timer.Change(0, _tickIntervalMilliseconds);
    }

    public void Stop()
    {
        _timer.Change(Timeout.Infinite, Timeout.Infinite);
    }

    private void DoWork()
    {
        try
        {
            _periodicWork.Invoke();
        }
        finally
        {
            Interlocked.Decrement(ref _currentActiveCount);
        }
    }
    private void OnTick()
    {
        _timer.Change(Timeout.Infinite, Timeout.Infinite);
        try
        {
            if (_currentActiveCount >= _maxThreadCount) return;

            Interlocked.Increment(ref _currentActiveCount);
            ThreadPool.QueueUserWorkItem(_ => DoWork());
        }
        finally
        {
            _timer.Change(_tickIntervalMilliseconds, _tickIntervalMilliseconds);
        }
    }

    public void Dispose()
    {
        _timer.Dispose();
    }
} 

class Program
{
    private static object _lockObject = new object();
    private static int _runningTasks = 0;

    private static void PrintToConsole()
    {
        lock (_lockObject)
        {
            _runningTasks += 1;
        }
        try
        {
            Console.WriteLine("Starting work. Total active: {0}", _runningTasks);
            var r = new Random();
            System.Threading.Thread.Sleep(r.Next(3500));                
        } finally
        {
            lock (_lockObject)
            {
                _runningTasks -= 1;
            }                
        }
    }
    static void Main(string[] args)
    {
        using (var w = new MaxThreadCountWorker(3, 150, PrintToConsole))
        {
            w.Start();
            Console.ReadKey();
        }
    }
}

这篇关于Windows Service定期产生最大线程数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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