请原谅我的术语,我对 System.Threading
不太熟悉,但如果我有如下内容:
private static int _index;
private static List<int> _movieIds = new List<int>();
static void Main(string[] args)
{
// the below call populates the _movieIds list variable with around 130,000 ints
GetListOfMovieIdsFromDatabase();
_index = 0;
Thread myThread = new Thread(DoWork);
myThread.Start();
}
public static void DoWork()
{
// do something with the value of _index (iterate through the _movieIds list) then recursively call DoWork() again
Thread.Sleep(400);
_index++;
DoWork();
}
这是不好的做法吗?我正在遍历
int's
的私有(private)静态列表在类级别定义为成员,因此 DoWork()
的第一次迭代将使用 _index
的第一个值(为了简单起见,我没有解释),那么第二次迭代(递归调用)将使用第二个值 _index
, 等等。我问这个的原因是因为在运行这个应用程序大约 12 小时后我得到了一个堆栈溢出异常,我相信这是因为递归调用。
最佳答案
是的。您最终总会出现堆栈溢出,因为调用堆栈永远没有机会展开。
而不是增加你的index
通过递归调用变量,在你的线程中使用循环。
public static void DoWork()
{
while(true)
{
// do something with the value of _index (iterate through the _movieIds list) then recursively call DoWork() again
Thread.Sleep(400);
_index++;
// break when a condition is met
}
}
关于c# - 递归调用线程方法(System.Threading)是不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19340182/