Mik*_*rks 1 c# recursion multithreading
原谅我的术语,我不是那么熟悉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();
}
Run Code Online (Sandbox Code Playgroud)
这是不好的做法吗?我正在迭代通过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
}
}
Run Code Online (Sandbox Code Playgroud)