我真的不明白这个错误是如何在这段代码中发生的。请自行查看代码
void dispatcherTimer_Tick(object sender, EventArgs e)
{
string srUrl = lstLocalIndex[irLocalIndex] + lstMainIndex[irMainIndex].Replace("0;","");
Task.Factory.StartNew(() =>
{
startNewWindow(srUrl);
});
}
void startNewWindow(string srUrl)
{
NewWindowThread<TitleWindow, string>(c => new TitleWindow(c), srUrl);
}
现在这段代码就是错误发生的地方。我也会附上截图
private void NewWindowThread<T, P>(Func<P, T> constructor, P param) where T : Window
{
Thread thread = new Thread(() =>
{
T w = constructor(param);
w.Show();
w.Closed += (sender, e) => w.Dispatcher.InvokeShutdown();
try
{
System.Windows.Threading.Dispatcher.Run();
}
catch
{
}
});
thread.SetApartmentState(ApartmentState.STA);
try
{
thread.Start();
}
catch
{
}
}
这个错误会导致整个软件抛出错误并停止工作,即使我在新线程中调用它们:(
这行抛出错误System.Windows.Threading.Dispatcher.Run();
另请检查截图
C# 4.0 WPF
我一直在与一位客户解决这个问题,这就是我的发现。
我们正在开发一个 WPF 应用程序,该应用程序执行大量线程和后台工作处理。这个异常突然开始出现,我开始进行一些挖掘。经过大约一个小时的调查,我终于找到了罪魁祸首:
var worker = new BackgroundWorker();
worker.DoWork += (o, ea) => Dispatcher.BeginInvoke(new Action(() =>
{
//do some heavy processing here, plus UI work, then call another method.
//inside that other method, I found this:
var thread = new Thread(() =>
{
//do some heavy processing.
}) { IsBackground = true };
thread.Start();
}));
似乎正在发生的事情是后台工作人员正在完成其工作并从执行中返回。但是,在该后台工作程序中创建的线程未完成处理,返回时仅发现创建它的线程已经超出范围,从而导致 AccessViolationException。
为了调试这个问题,我建议密切关注异常发生的位置并仔细检查您的调用堆栈,该堆栈可能已被破坏或丢失,具体取决于抛出异常时您是否位于线程内。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)