星期二, 10月 20, 2020

[C#] BackgroundWorker - Exception

使用 BackgroundWorker 時發現執行到一半就結束的情況,沒有 Exception 拋出,直覺是 Exception 被吃掉了,查之前筆記 - [C#] BackgroundWorker 範例4 發現,Exception 必須在 RunWorkerCompleted Event 內處理,之前筆記時沒有意識到這點,單獨在紀錄一下

官方文章說明 - BackgroundWorker.DoWork
If the operation raises an exception that your code does not handle, the BackgroundWorker catches the exception and passes it into the RunWorkerCompleted event handler, where it is exposed as the Error property of System.ComponentModel.RunWorkerCompletedEventArgs. If you are running under the Visual Studio debugger, the debugger will break at the point in the DoWork event handler where the unhandled exception was raised. If you have more than one BackgroundWorker, you should not reference any of them directly, as this would couple your DoWork event handler to a specific instance of BackgroundWorker. Instead, you should access your BackgroundWorker by casting the sender parameter in your DoWork event handler.
namespace BackgroundWorkerException
{
    public partial class Form1 : Form
    {
        private BackgroundWorker worker = new BackgroundWorker();

        public Form1()
        {
            InitializeComponent();
            worker.DoWork += Worker_DoWork;
            worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
        }

        private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // DoWork 內發生 Exception,會存放在 RunWorkerCompletedEventArgs.Error 內,
            // 所以 BackgroundWorker Exception 必須在 RunWorkerCompleted 內處理
            if (e.Error != null)
                MessageBox.Show(e.Error.Message);
        }

        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            throw new Exception("從 DoWork 內拋出 Exception");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            worker.RunWorkerAsync();
        }
    }
}
[C#] BackgroundWorker - Exception

沒有留言:

張貼留言