Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 系统。计时器在单独的线程中运行,并保持线程限制_C#_.net_Wcf_Timer_Threadpool - Fatal编程技术网

C# 系统。计时器在单独的线程中运行,并保持线程限制

C# 系统。计时器在单独的线程中运行,并保持线程限制,c#,.net,wcf,timer,threadpool,C#,.net,Wcf,Timer,Threadpool,我想限制多线程WCF服务中的线程数。因此,我使用ThreadPool.SetMaxThread函数。现在,我想使用System.Timers以给定的间隔生成事件 但是,我的服务同时收到许多要在线程池中执行的操作。当我的计时器过期时,该操作将在线程池中排队(我有时预期有100000个任务),因此执行速度较慢 有没有办法执行我之前的已用事件?例如,通过设置线程池上排队的任务优先级?或在线程池之外运行事件 我希望在我的服务中保持线程的全局限制。如果您只需要限制线程数以保护拒绝服务攻击,那么更好的选择是

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

但是,我的服务同时收到许多要在线程池中执行的操作。当我的计时器过期时,该操作将在线程池中排队(我有时预期有100000个任务),因此执行速度较慢

有没有办法执行我之前的已用事件?例如,通过设置线程池上排队的任务优先级?或在线程池之外运行事件


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

如果您只需要限制线程数以保护拒绝服务攻击,那么更好的选择是限制
服务节流行为的
maxConcurrentCalls
属性。 详情请参阅

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

如果是这样,则可以避免限制线程池的最大线程数


然后,您的WCF服务将不会受到多个并发调用的影响,同时计时器事件将被毫不延迟地处理。

如果有选择,您可以将代码转换为支持生产者-消费者模式,方法是将
Taskfactory
与阻塞集合结合使用

集合允许您设置最大限制

从以下链接:

-可选最大容量。

- 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.
以下是一些值得查看的资源:




这篇.NET Matters MSDN文章有点老了,但我认为这种方法仍然有效。他的解决方案是创建一个ThreadPriorityPool,定义托管池中的下一个可用线程应该执行什么


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

否我不想限制并发调用,但要限制服务中的线程数,因为每个调用都将在多个线程中同时分析和运行。
ThreadPool
中没有内置的设置任务优先级的功能。我们讨论了类似的问题,谢谢你的回答。但是,对于第一个解决方案,我的问题是只有经过的计时器事件应该在另一个线程上以高优先级触发。和计时器在线程池中自动启动。。。
- 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.