原谅我的术语,我不是很熟悉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
在类级别定义为成员的私有静态列表,因此的第一次迭代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
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句