簡體   English   中英

使用 BackgroundWorker 處理異常

[英]Handling exception with BackgroundWorker

在 WinForms 應用程序中,在觸發BackgroundWorker.DoWork事件時運行的方法中發生異常。

System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
worker.DoWork += import_begin;
System.Objects arguments = new System.Object[] {filename, why};
worker.RunWorkerAsync(arguments);

private void import_begin(System.Object sender, System.ComponentModel.DoWorkEventArgs args)
{
    // unpack the arguments
    System.String filename = (System.String)arguments[0];

    // exception is occurring here
    Controller.Excel excel = new Controller.Excel(filename);
}

我已經設置了斷點來確定拋出異常的位置,並且它位於上面注釋的代碼行中。 即使在處理完異常之后,也會出現一個對話框:

“調用的目標已拋出異常”。 在此處輸入圖片說明

是否可以阻止此對話框?

順便說一下,異常是InvalidDataException類型,因為嘗試導入的文件類型無效。

編輯:部分Controller.Excel代碼:

class Excel
{
    protected OfficeOpenXml.ExcelPackage excel;
        protected const int HEADER_ROW_OFFSET = 7;
        System.Globalization.CultureInfo provider;

        // ctor
        public Excel(System.String filename)
        {

            excel = new OfficeOpenXml.ExcelPackage(new System.IO.FileInfo(filename));
            excel.Compatibility.IsWorksheets1Based = false;
            provider = System.Globalization.CultureInfo.InvariantCulture;

        }
}

操作:

它使用標准的文件對話框形式。 它旨在讓用戶打開 .xlsx 文件,每當他們嘗試打開任何其他文件類型時都會發生此異常

我聽起來好像你只是想在用戶以某種方式選擇一個不是 Excel 文件和/或損壞的文件時優雅地處理這種情況。

將您的代碼更改為以下內容:

private void import_begin(System.Object sender, System.ComponentModel.DoWorkEventArgs args)
{
    // unpack the arguments
    System.String filename = (System.String)arguments[0];

    // you probably should inspect the file extension in `filename` to see if it
    // is at least .xls or .xlsx prior to using Controller

    try
    {   
        Controller.Excel excel = new Controller.Excel(filename);
        ...        
    }
    catch (InvalidDataException ex)
    {
        // gracefully handle the error
        ...
    }
    catch (Exception ex)
    {
        // eat, don't want thread to unwind
    }
}

現在,如果他們選擇任何其他文件類型或文件是損壞的 Excel 文件,將調用上面的catch處理程序,您可以在其中優雅地處理這種情況。

通常你不應該從一個 worker 更新 UI,但是MessageBox有它自己的消息泵。

提示

為了保持整潔,您可能需要在運行BackgroundWorker之前檢查文件的擴展名。 這是一個快速檢查的快速勝利,並將所有與 UI 相關的活動保留在主線程中,而不是在事情變得更加復雜的子線程中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM