【问题标题】:System.Timer elapsed in separate thread and keeping the thread limitSystem.Timer 在单独的线程中过去并保持线程限制
【发布时间】:2012-11-11 00:30:35
【问题描述】:

我想限制我的多线程 WCF 服务中的线程数。所以,我使用ThreadPool.SetMaxThread 函数。现在,我想使用System.Timers 以给定的时间间隔生成事件。

但是,我的服务同时接收到许多要在线程池中执行的操作。当我的计时器用完时,该操作会在 ThreadPool 中排队(我有时期望有 100,000 个任务),因此执行速度很慢。

之前有没有办法执行我的已逝事件?例如,通过设置线程池上排队的优先级任务?还是在线程池之外结束了事件?

我想在我的服务中保持我的全局线程限制。

【问题讨论】:

    标签: c# .net wcf timer threadpool


    【解决方案1】:

    如果您只需要限制线程数来保护拒绝服务攻击,那么更好的选择是限制maxConcurrentCalls 属性为ServiceThrottlingBehavior。 详情见http://msdn.microsoft.com/en-us/library/system.servicemodel.description.servicethrottlingbehavior.maxconcurrentcalls.aspx

    默认情况下,此参数是处理器计数的 16 倍。

    如果是这样,那么您可以避免限制线程池的最大线程数。

    那么从多个并发调用的角度来看,您的 WCF 服务将是安全的,同时将无延迟地处理计时器事件。

    【讨论】:

    • 不,我不想限制并发调用,但要限制我的服务中的线程数,因为每个调用都会被分析并同时在多个线程中运行......
    • ThreadPool 中没有设置任务优先级的内置功能。讨论了类似的问题here
    【解决方案2】:

    如果可以的话,您可以通过结合使用 Taskfactory 与阻塞集合来转换您的代码以支持生产者-消费者模式。

    集合允许您设置最大限制。

    从下面的链接:

    - An implementation of the Producer-Consumer pattern.
    
    - Concurrent adding and taking of items from multiple threads.
    

    > - 可选的最大容量。

    - Insertion and removal operations that block when collection is empty or 
      full.
    
    - Insertion and removal "try" operations that do not block or that block
      up to a specified period of time.
    
    - Encapsulates any collection type that implements
      IProducerConsumerCollection(Of T)
    
    - Cancellation with cancellation tokens.
    
    - Two kinds of enumeration with foreach (For Each in Visual Basic):
    
        - Read-only enumeration.
    
        - Enumeration that removes items as they are enumerated.
    

    以下是一些值得一试的资源:

    blocking-collection-and-the-producer-consumer-problem
    http://msdn.microsoft.com/en-us/library/dd997371.aspx
    http://msdn.microsoft.com/en-us/library/dd267312.aspx

    【讨论】:

      【解决方案3】:

      这篇 .NET Matters MSDN 文章 ThreadPoolPriority, and MethodImplAttribute 有点旧,但我认为该方法仍然有效。他的解决方案是创建一个 ThreadPriorityPool 来定义托管池中下一个可用线程应该执行的内容。

      另一种选择是在 CodeProject 上尝试Smart Thread Pool。它明确支持按优先级排序工作项。

      【讨论】:

      • 感谢您的回答。但是,对于您的第一个解决方案,我的问题是只有经过的计时器事件才应该在另一个线程上以高优先级触发。并且定时器在threadPool中自动启动...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-11
      • 2015-05-26
      相关资源
      最近更新 更多