C#背景线程 [英] C# Background Thread

查看:221
本文介绍了C#背景线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我描述一下我要达到的目标.我正在用C#编程.

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

我有一个函数(方法)DoCalculations().我想递归调用此DoCalculations()方法.但是,在C#中,我将异常作为未处理的异常System.StackOverflow获得. 因此,我试图在后台线程上运行DoCalculations()方法.

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.

在FORM LOAD事件上.我已经完成以下工作:-

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)
    {
    }

我打算在上述While循环中连续运行方法DoCalculations().

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

DoCalculations()
{
//some calculations.

}

我确实在DoCalculations()方法中获得了控制权.但是,我想立即执行此操作.

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.

我在VB.NET中使用了上面的方法,这让我更加困惑为什么它不能在C#.NET中工作

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

任何帮助,都非常感谢您发表评论.

Any assistance, comments greatly appreciated.

谢谢 AP

推荐答案

首先,使用后台工作程序,因为它更易于使用且速度更快.

First, use a background worker, as it is easier to use and faster.

第二,您的循环代码应放在后台线程中.

Second, your looping code should go in the background thread.

这里有一些代码可以帮助您入门.

Here is some code to get you started.

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

...

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

听起来您只是在尝试解决堆栈溢出问题,而不知道如何解决.忘记多线程,而不是递归调用DoCalculations,而是在循环中调用它,并确保循环知道何时终止.另外,如果您不想在此期间锁定GUI,则最好还是使用后台线程.

It sounds like you are just trying to fix a stack overflow, and not knowing how to do so. Forget the multithreading, instead of calling DoCalculations recursively, call it in a loop, and make sure that the loop knows when to terminate. Also, if you don't want to lock up the GUI during this time, then a background thread is better anyway.

这篇关于C#背景线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆