我可以使用什么同步?

时间:2016-10-20 09:30:56

标签: c#

我在C#工作,并且正在寻找一种机制来同步我的应用程序。

我有一个函数来管理我的应用程序中的异常,处理多线程。当引发异常时,会调用一个函数,进行一些处理并要求用户进行检查。

如果在第一个正在进行时引发新的异常,我想等待第一个并且在执行完第一个之后无所事事

我该如何正确地做到这一点?

我的选秀:

private void onAnomaly(enumAnomaly err)
{
    if (anomalyInProgress)
        //wait
        return;
    else
        anomalyInProgess = true;
        //do something
        anomalyInProgess = false;
}

3 个答案:

答案 0 :(得分:0)

您可以使用Interlocked.Exchange method

编辑根据您的评论,您需要等待其他功能。您可以通过添加锁定对象来完成此操作。

private int anomalyInProgress = 0;
private Object _lock = new Object();

private void onAnomaly(enumAnomaly err)
{
    //Here, the value of anomalyInProgress will be set to 1, but
    // Exchange return the value before the change.
    // So if it was 0 before, it means nobody is already executing this code
    //and we can safely enters
    if (0 == Interlocked.Exchange(anomalyInProgress, 1))
    {
        lock (_lock)
        {
            //do something

            //we reset the value of anomalyInProgress so the next one can enter in safely
            Interlocked.Exchange(anomalyInProgress, 0)
        }
    } 
    else 
    {
        //I cannot take the lock directly, because I could be taking it before the 'True' condition.
        Threading.Thread.Sleep(1)
        lock (_lock) //This will wait for the 'True' condition to finish
        {
        }
    }
}

答案 1 :(得分:0)

我找到了一种带锁的方法,也许不是最好的,但似乎有效

private object anomalyLock = new object();
private Queue<enumAnomaly> anomalyQueue = new Queue<enumAnomaly>();

private void onAnomaly(enumAnomaly err)
{
    anomalyQueue.Enqueue(err);

    lock (anomalyLock)
    {
        if (anomalyQueue.Count == 0)
            return;

        //do something

        // UserAck

        anomalyQueue.Clear();
    }
}

有最好的方法吗?

答案 2 :(得分:-1)

当引发异常时,您可以锁定您调用的功能

object lockObj = new object();
lock(lockObj)
{
    //function called once anomaly raised
}

希望这有帮助。

相关问题