簡體   English   中英

System.Timer在單獨的線程中經過並保持線程限制

[英]System.Timer elapsed in separate thread and keeping the thread limit

我想限制我的多線程WCF服務中的線程數。 因此,我使用ThreadPool.SetMaxThread函數。 現在,我想使用System.Timers以給定的時間間隔生成事件。

但是,與此同時,我的服務收到許多要在線程池中執行的動作。 當我的計時器過去時,該動作在ThreadPool中排隊(我有時期望有100,000個任務),因此執行緩慢。

有沒有辦法執行我過去的事件? 例如,通過設置優先級任務在線程池上排隊? 還是在線程池外發生了事件?

我想在服務中保留線程的全局限制。

如果您只需要限制線程數以保護拒絕服務攻擊,那么更好的選擇是限制ServiceThrottlingBehavior maxConcurrentCalls屬性。 請參閱http://msdn.microsoft.com/zh-cn/library/system.servicemodel.description.servicethrottlingbehavior.maxconcurrentcalls.aspx中的詳細信息

默認情況下,此參數是處理器計數的16倍。

如果是這樣,則可以避免限制線程池的最大線程數。

這樣,從多個並發調用的角度來看,您的WCF服務將是安全的,同時將處理計時器事件而不會延遲。

您可以選擇使用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. 

以下是一些值得檢查的資源:

阻止收集和生產者消費者的問題
http://msdn.microsoft.com/en-us/library/dd997371.aspx
http://msdn.microsoft.com/en-us/library/dd267312.aspx

有關.NET的MSDN文章ThreadPoolPriority和MethodImplAttribute有點陳舊,但我認為該方法仍然有效。 他的解決方案是創建一個ThreadPriorityPool,該線程定義托管池中下一個可用線程應執行的操作。

另一種選擇是嘗試在CodeProject上使用智能線程池 它明確支持按優先級排序工作項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM