5

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

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
    }
}

这在我描述的场景中使用安全吗?

4

2 回答 2

5

是的,它看起来很安全,因为int这里是原子类型。但我仍然建议更换

private static int _isSampling;

private static object _samplingLock = new object();

并使用:

lock(_samplingLock)
{
    Sample sample = new Sample();
    sample.PerformSampling(automation);
   _lastSample = sample;
}

仅仅因为它是推荐的模式,并且还确保对 _lastSample 的所有访问都得到正确处理。

注意:我希望速度相当,lock 使用在内部使用 Interlocked 的托管 Monitor 类。

编辑:

我错过了退避方面,这是另一个版本:

   if (System.Threading.Monitor.TryEnter(_samplingLock))
   {
     try
     {
         .... // sample stuff
     }
     finally
     {
          System.Threading.Monitor.Exit(_samplingLock);
     }
   }
于 2010-04-07T21:27:30.080 回答
-1

我通常声明一个 volatile bool 并执行以下操作:

private volatile bool _isBusy;
private static Sample _lastSample;

private Sample DoSomething()
{
     lock(_lastSample)
     {
       if(_isBusy)
          return _lastSample;
       _isBusy = true;
     }

     try
     {
       _lastSample = new sameple//do something
     }
     finally
     {
        lock(_lastSample)
        {
           _isBusy = false;
        }
     }
     return _lastSample;
} 
于 2010-04-07T21:37:44.663 回答