我希望有一个锁可以阻止从相同的线程输入一段代码,使其从无限递归中更加无懈可击。就是这样:
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.TryEnter
,SemaphoreSlim
等)只能获得一个排除不同线程的锁定;在这里使用它们只会导致堆栈溢出。
这需要在.NET 2中。
顺便说一句,我知道这个要求表明代码非常糟糕,而且代码重写真的更合理。如果.NET提供类似的东西,我仍然感兴趣。
答案 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;
}
}
但是,我会说以这种方式试图解决“无限递归”问题有些可疑。我本以为应该有更好的方法来修复逻辑 - 这看起来像是一种贴膏药的方法。