递归锁定(即在同一个线程上工作的锁)

时间:2018-06-05 08:52:21

标签: c# .net-2.0

我希望有一个锁可以阻止从相同的线程输入一段代码,使其从无限递归中更加无懈可击。就是这样:

private static object RecurseLock = new object();
public void PartiallyRecursiveMethod()
{
    if (TryEnter(RecurseLock))
    {
        try
        {
            Console.WriteLine("Hello ");
            // we want to do it again now
            PartiallyRecursiveMethod();
        }
        finally
        {
            Release(RecurseLock);
        }
    }
    Console.WriteLine("world!");
}

这样调用PartiallyRecursiveMethod的输出就是“ Hello world!”。 (或者可能在那里有换行符,我忘记Console.WriteLine如何工作)

TryEnter应仅适用于当前线程。不应阻止其他线程。

C#中有什么东西可以做到这一点,还是我必须自己编写?我相信所有常见的嫌疑人(Monitor.TryEnterSemaphoreSlim等)只能获得一个排除不同线程的锁定;在这里使用它们只会导致堆栈溢出。

这需要在.NET 2中。

顺便说一句,我知道这个要求表明代码非常糟糕,而且代码重写真的更合理。如果.NET提供类似的东西,我仍然感兴趣。

1 个答案:

答案 0 :(得分:1)

正如几位人士所指出的那样,在.Net 2.x中,您可以使用[ThreadStatic]

using System;
using System.Threading;
using System.Threading.Tasks;

namespace Demo
{
    class Program
    {
        static void Main()
        {
            Parallel.Invoke(test, test, test);
        }

        static void test()
        {
            if (_thisThreadAlreadyHere)
            {
                Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} is already working.");
                return;
            }

            _thisThreadAlreadyHere = true;

            try
            {
                Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} is working.");

                Thread.Sleep(1000);
                test();
                Thread.Sleep(1000);

                Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} has completed.");
            }

            finally
            {
                _thisThreadAlreadyHere = false;
            }
        }

        [ThreadStatic]
        static bool _thisThreadAlreadyHere;
    }
}

但是,我会说以这种方式试图解决“无限递归”问题有些可疑。我本以为应该有更好的方法来修复逻辑 - 这看起来像是一种贴膏药的方法。