我有一個採樣的系統。我在應用程序中有多個客戶端線程對這些示例感興趣,但實際進行示例的過程只能在一個上下文中進行。它足夠快,可以阻止調用進程,直到完成採樣,但足夠慢,我不希望多個線程堆積請求。我想出了這個設計(精簡到最小的細節):這是一個正確的聯鎖同步設計嗎?
public class Sample
{
private static Sample _lastSample;
private static int _isSampling;
public static Sample TakeSample(AutomationManager automation)
{
//Only start sampling if not already sampling in some other context
if (Interlocked.CompareExchange(ref _isSampling, 0, 1) == 0)
{
try
{
Sample sample = new Sample();
sample.PerformSampling(automation);
_lastSample = sample;
}
finally
{
//We're done sampling
_isSampling = 0;
}
}
return _lastSample;
}
private void PerformSampling(AutomationManager automation)
{
//Lots of stuff going on that shouldn't be run in more than one context at the same time
}
}
這是安全在我描述的場景使用?
+ 1爲更簡單的解決方案。 – 2010-04-07 21:36:43
從維護角度來看,TryEnter可能更好,因爲與Interlocked.CompareExchange相比,大多數人可能會熟悉Monitor.TryEnter。在這種情況下,我並不擔心開銷,因爲我只是每秒採樣幾次。當它確實執行採樣時,我敢肯定,採樣過程本身的開銷將比鎖定基元多得多。 – 2010-04-07 21:56:34
我喜歡Monitor.TryEnter,但是我們不應該使用ReaderWriterLockSlim這些天? http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim_members.aspx – 2010-04-07 21:57:12