0

Let me describe what I am trying to achieve. I am programming in C#.

I have a function (method) DoCalculations(). I want to call this DoCalculations() method recursively. However, in C# I get exception as unhandled exception System.StackOverflow. So, I am trying to run DoCalculations() method on a back ground thread.

On FORM LOAD event. I have done following:-

Thread objThread = new Thread(new ThreadStart(DoCalculations));

On START BUTTON CLICK event. I am starting the Thread as follows.

 objThread.IsBackground = true;
    objThread.Start();
    while (!objThread.IsAlive)
    {
    }

And I intend to run method DoCalculations() continuously with above While Loop.

DoCalculations()
{
//some calculations.

}

I do get control in DoCalculations() method one time. However, I want to do this every instant.

Please if any one can assist me with regards to back ground thread, or is there any better way to achieve to do parallel computation.

I have used above approach in VB.NET, making me more confused why its not working in C#.NET

Any assistance, comments greatly appreciated.

Thanks AP

4

5 回答 5

3

首先,使用后台工作者,因为它更容易使用且速度更快。

其次,您的循环代码应该进入后台线程。

这是一些帮助您入门的代码。

BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += bw_DoWork;
bw.RunWorkerAsync();

...

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    while (someCondition)
    {
        DoCalculations();
    }
}

编辑:听起来你只是想修复堆栈溢出,而不知道如何去做。忘记多线程,而不是递归调用 DoCalculations,而是在循环中调用它,并确保循环知道何时终止。此外,如果您不想在此期间锁定 GUI,那么无论如何最好使用后台线程。

于 2012-06-22T11:19:28.543 回答
1

System.Threading.Timer 提供一种以指定时间间隔执行方法的机制。

如何在您的情况下使用....

using System.Threading;

声明定时器回调和定时器对象如下..

 private TimerCallback calculateTimerDelegate = null;
 private System.Threading.Timer calculationTimer = null;

并在您的 Load() 事件中初始化它们..

calculateTimerDelegate = new TimerCallback(DoCalculation);
calculationTimer = new Timer(calculateTimerDelegate , null, 10000, (1 * 60 * 1000));

现在,你的计算方法......

DoCalculations()
{
    //some calculations.
}
于 2012-06-22T11:17:35.737 回答
0

如果您遇到堆栈溢出异常,则不会通过引入多线程来发现使其消失的方法。您的递归代码中有一个错误。

于 2012-06-22T11:15:24.370 回答
0

如果你想在后台线程上重复运行它,你可以使用这样的System.Threading.Timer类:

var timer = new Timer( DoCalculations, null, TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(1));

这将每秒运行您的计算。如果要调整时间,请更改最后一个TimeSpan参数。

于 2012-06-22T10:54:04.100 回答
0

使用 BackgroundWorker 类

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

于 2012-06-22T11:05:57.340 回答