请帮我理解出了什么问题。我有一个进度条方法来开始在任务中运行进度条。 Base类是静态类,它保存来自另一个类的更新值。以下是我的代码:
private void startProgressBarBA()
{
int tempBA = 0;
proBing.Maximum = Int32.Parse(cboGeoThreshold.Text);
CancellationTokenSource bingBarToken = new CancellationTokenSource();
Task bingTask = Task.Factory.StartNew(() =>
{
while (!bingBarToken.Token.IsCancellationRequested)
{
if (tempBA != Base.proBaValue)//Reduce the number of same value assigned.
{
try
{
Dispatcher.BeginInvoke(new Action(() =>
{
if (proBing.Value == proBing.Maximum)
{
proBing.Value = 0;
Base.proBaValue = 0;
}
proBing.Value = Base.proBaValue;
tempBA = Base.proBaValue;
baRecord.Content = proBing.Value + "/" + proBing.Maximum;
}
));
}
catch(OutOfMemoryException e)
{
throw e;
}
}
if (Base.checkTaskBA == false)
{
bingBarToken.Cancel();
}
}
},bingBarToken.Token, TaskCreationOptions.LongRunning,TaskScheduler.Default);
}
异常将在一段时间后发生,并且
Dispatcher.BeginInvoke
已经突出显示。以下是异常消息:
System.OutOfMemoryException was unhandled by user code
HResult=-2147024882
Message=Exception of type 'System.OutOfMemoryException' was thrown.
Source=View
StackTrace:
at View.MainWindow.<>c__DisplayClass21_0.<startProgressBarBA>b__0() in C:\Wade\GeocodingApp\Geocoder_v21_Rev_pcode\View\MainWindow.xaml.cs:line 331
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
InnerException:
如何解决这个问题?是因为
new Action()
导致OutOfMemoryException?谢谢大家的帮助。
答案 0 :(得分:2)
这里只是一个猜测,但看起来你没有延迟#34;而#34;在你的任务中循环。
这意味着你很快就在循环中循环,并且正在创建大量的异步&#34;调用&#34; Dispatcher
队列上的消息 - 毫无疑问,这会耗尽所有内存......它们的处理速度不够快,因此正在建立起来(即必须有100多万/几百万&#34 ;动作&#34;创建的对象。)
可能的解决方案....放一些&#34;等待&#34;在你的while循环中,例如Thread.Sleep(100)
- 您不需要经常发送它们以表明进度。
private void startProgressBarBA()
{
int tempBA = 0;
proBing.Maximum = Int32.Parse(cboGeoThreshold.Text);
CancellationTokenSource bingBarToken = new CancellationTokenSource();
Task bingTask = Task.Factory.StartNew(() =>
{
while (!bingBarToken.Token.IsCancellationRequested)
{
if (tempBA != Base.proBaValue)//Reduce the number of same value assigned.
{
try
{
Dispatcher.BeginInvoke(new Action(() =>
{
if (proBing.Value == proBing.Maximum)
{
proBing.Value = 0;
Base.proBaValue = 0;
}
proBing.Value = Base.proBaValue;
tempBA = Base.proBaValue;
baRecord.Content = proBing.Value + "/" + proBing.Maximum;
}
));
}
catch(OutOfMemoryException e)
{
throw e;
}
}
if (Base.checkTaskBA == false)
{
bingBarToken.Cancel();
}
Thread.Sleep(100);
}
},bingBarToken.Token, TaskCreationOptions.LongRunning,TaskScheduler.Default);
}