[英]Return from BackgroundWorker.DoWork throws TargetInvocationException
我無法獲得此異常的原因:
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.Reflection.TargetInvocationException'的未處理異常附加信息:調用的目標已引發異常。
目標(據我有限的理解)是背景工作人員的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搜索最明顯的查詢已經完成。
每當遇到TargetInvocationException
時要TargetInvocationException
就是InnerException
屬性,該屬性將具有“真實”異常。
從外觀上看,它很可能與嘗試從工作線程內部訪問GUI有關。 請記住,使用DoWork
處理程序時,代碼在與主UI不同的線程中執行。 因此,對GUI組件的調用必須通過Invoke
調用完成,或者完全避免。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.