请帮我了解一下出了什么问题。我有一个进度条方法来开始在一个任务中运行进度条。基类是静态类,它保存来自另一个类的更新值。下面是我的代码:
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?谢谢大家的帮助。
发布于 2017-04-18 00:38:53
只是在这里猜测一下,但是看起来任务中的"while“循环没有任何延迟。
这意味着您正在非常快地遍历该循环,并且正在Dispatcher队列上创建大量异步“调用”消息--毫无疑问,这正在耗尽所有memory....they处理不够快的时间,因此正在生成(即必须创建了1000万/数百万"Action“对象)。
可能的solution....put在wait循环中的某种“等待”,例如一个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);
}https://stackoverflow.com/questions/43461270
复制相似问题