简体   繁体   English

在C#上使用backgroundworker的OutOfMemory异常:在没有backgroundworker的情况下可以正常工作

[英]OutOfMemory Exception using backgroundworker on C# : works fine without backgroundworker

I'm writing a project in C# and I've run into a problem using backgroundworker to keep my form responsive whilst an expensive process runs. 我正在用C#编写一个项目,但是使用backgroundworker在保持昂贵的流程运行时使表单保持响应状态时遇到了问题。 When I use the bgw method, I get an OutOfMemory exception. 当我使用bgw方法时,出现了OutOfMemory异常。 However, if I just run my ExpensiveMethod() directly without using bgw then I don't have any issues. 但是,如果我不使用bgw就直接运行ExpensiveMethod(),那么我不会有任何问题。 Any ideas? 有任何想法吗? I really want to be able to implement a progress bar whilst this method runs (its quite a time consuming process and the user needs to know how long is left). 我真的希望能够在此方法运行时实现进度条(这是一个非常耗时的过程,并且用户需要知道还剩下多长时间)。 I am fairly new to C# and definitely a novice with threading. 我对C#相当陌生,而且绝对是线程新手。

Here is how I'm implementing my bgw and ExpensiveMethod(): 这是我实现bgw和ExpensiveMethod()的方式:

 private void btnGo_Click(object sender, EventArgs e)
 {
     myProgressBar.Visible = true;
     bgw.RunWorkerAsync();           
 }


 private void bgw_DoWork(object sender, DoWorkEventArgs e)
 {
     ExpensiveMethod();
 }

private void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
 { 
     myProgressBar.Value = e.ProgressPercentage;
 }

 private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {       
     myProgressBar.Visible = false;
 }


private void ExpensiveMethod()
{
    // do a big calculation and call this every so often:
    bgw.ReportProgress((int)percentComplete);

}

This method, however, works fine with no memory exceptions, but obviously locks up the form whilst it runs: 但是,此方法可以在没有内存异常的情况下正常工作,但显然可以在运行时锁定表单:

private void btnGoThatWorks_Click(object sender, EventArgs e)
{
    ExpensiveMethod();            
}

Any ideas? 有任何想法吗? I am on Windows7 32-bit. 我在Windows7 32位上。

It appears that the answer was that I was calling bgw.ReportProgress((int)percentComplete); 看来答案是我在打电话bgw.ReportProgress((int)percentComplete); far too often --- changing the code so it only reports every few percent seems to have fixed the issue. -经常更改代码,以便仅报告百分之几的代码似乎已解决了该问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM