官方文章說明 - 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();
}
}
}
沒有留言:
張貼留言