我无法理解此异常的原因:
private void bwWorker_DoWork(object sender, DoWorkEventArgs e)
{
if (Main.bolDebugMode)
MessageBox.Show("Function DoWork is called");
if (Main.ftpsync(Main.strUsername407, Main.strPassword407, sender as BackgroundWorker) == 0)
e.Result = e.Result + "No error in " + Main.strUsername407;
else
{
if (Main.bolDebugMode)
MessageBox.Show("Errors in " + Main.strUsername407);
e.Cancel = true;
e.Result = e.Result + "Errors in " + Main.strUsername407;
if (Main.bolDebugMode)
MessageBox.Show("Errors marked");
try
{
MessageBox.Show("Next step throws exception");
return;
}
catch (Exception error)
{
if (error.ToString() != null)
MessageBox.Show(error.InnerException.Message);
}
}
}
抛出此异常:
类型为' System.Reflection.TargetInvocationException'的未处理异常。发生在mscorlib.dll中
附加信息:调用目标引发了异常。
目标(据我有限的理解)是后台工作者的RunWorkerCompleted功能:
private void bwWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (Main.bolDebugMode) MessageBox.Show("DoWork Completed. Break: " + e.Cancelled + " Error: " + e.Error + " Result: " + e.Result); // First, handle the case where an exception was thrown. if (e.Error != null) { lStatus.Text = e.Error.Message; } else if (e.Cancelled) lStatus.Text = "Cancelled: " + e.Result.ToString(); } else { lStatus.Text = "Done! " + e.Result; Thread.Sleep(Convert.ToInt16(Main.strGlobalWaitTime)); pbProgress.Value = 0; lStatus.Text = ""; } if (Main.bolDebugMode) MessageBox.Show("Analysis completed"); // Enable the Start button. btnStart.Enabled = true; // Disable the Cancel button. btnCancel.Enabled = false; }
public class Main
{
#region Variables
// Variables - FTP Settings
// Reading tons of variables from a appconfig file like so:
private static string StrGlobalWaitTime = ConfigurationManager.AppSettings["program_globalWaitTime"];
private static bool BolDeleteRemoteFiles = Convert.ToBoolean(ConfigurationManager.AppSettings["program_deleteremotefiles"]);
// Configuring the variables to receive and write
public static string strGlobalWaitTime
{
get { return StrGlobalWaitTime; }
set { StrGlobalWaitTime = value; }
}
#endregion
#region Main function
public static int ftpsync(string strUsername, string strPassword, BackgroundWorker bwWorker)
{
if (Directory.EnumerateFiles(strWorkDirectory, "*.pdf").Any())
{
bwWorker.ReportProgress(0, "Files left! Upload not complete");
Thread.Sleep(Convert.ToInt16(Main.strGlobalWaitTime));
return 1;
}
但是,它甚至无法到达第一个调试消息框。因此,它必须在函数的返回和开始之间发生。他是后台工作者不直接移交给RunWorkerCompleted函数吗?谁能告诉我我错过了什么或做错了什么?
这是我的第一个问题。我会尽量提供尽可能多的信息。 Google会搜索最明显的查询。
答案 0 :(得分:2)
遇到Razor
时要查找的内容是TargetInvocationException
属性,它将具有“真实”异常。
从它的外观来看,它很可能与尝试从工作者的线程内部访问GUI有关。请记住,在使用InnerException
处理程序时,代码将在与主UI不同的线程中执行。因此,对GUI组件的调用必须通过DoWork
调用完成,或者一起避免。