我有一个采样系统。我在应用程序中有多个对这些样本感兴趣的客户端线程,但获取样本的实际过程只能在一个上下文中发生。它足够快,可以阻止调用进程直到采样完成,但足够慢,我不希望多个线程堆积请求。我想出了这个设计(精简到最小的细节):
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
}
}
这在我描述的场景中使用安全吗?