我无法获得此例外的原因:
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);
}
}
}
它引发了以下例外:
在mscorlib.dll中出现了一个未经处理的类型'system.targetInvocation exception'
其他信息:例外是由调用的目标抛出的。
目标(对我有限的理解)是背景工作者的runworkercomplet功能:
私有void bwwrwworker_runworkercompleted(对象发送者,runworkercompletedeventargs e) { if(main.boldebugmode) MessageBox.Show(" Dowork完成。break:" e.cancelled " error:" e.error "结果:" e. result); //首先,处理抛出例外的情况。 如果(E.Error!= null) { lstatus.text = e.Error.message; } 否则(e.cancelled) lstatus.text ="取消:" e.Result.toString(); } 别的 { lstatus.text =" done!" e.Result; thread.sleep(convert.toint16(main.strglobalwaittime)); pbprogress.value = 0; lstatus.text ="; } if(main.boldebugmode) MessageBox.Show("分析已完成"); //启用开始按钮。 btnstart.enabled = true; //禁用取消按钮。 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;
}
但是,它甚至没有达到第一个调试消息框。因此,它必须在函数的返回和开始之间发生。他的背景工人不是直接移交给RunWorkerComplet的功能吗?谁能告诉我我想念或做错了什么?
这是我的第一个问题。我将尝试提供尽可能多的信息。Google搜索最明显的查询。
每当遇到TargetInvocationException
时要寻找的东西是InnerException
属性,它将具有"真实"例外。
从外观上看,它很可能与尝试从工人的线程中访问GUI有关。请记住,使用DoWork
处理程序时,代码在与主UI的不同线程中执行。因此,必须通过Invoke
调用或避免一起进行GUI组件的呼叫。