It appears that the answer was that I was calling bgw.ReportProgress((int)percentComplete); far too often --- changing the code so it only reports every few percent seems to have fixed the issue.
OutOfMemory Exception using backgroundworker on C# : works fine without backgroundworker
-
29-06-2023 - |
Question
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. When I use the bgw method, I get an OutOfMemory exception. However, if I just run my ExpensiveMethod() directly without using bgw then I don't have any issues. 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.
Here is how I'm implementing my bgw and 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.
Solution