当我把try catch块放在我执行任务的时候。在RunWorkerCompleted()方法中,e.error使用为null。当我删除try catch块然后在RunWorkerCompleted()方法中,e.error不等于null。
为什么这种奇怪的行为?
代码:
public partial class LoginForm : Form
{
private static BackgroundWorker bw = new BackgroundWorker();
private static ManualResetEvent mre = new ManualResetEvent(false);
enum status
{
Blank,
Success,
Error
};
public LoginForm()
{
InterimProceedings();
InitializeComponent();
}
private void InterimProceedings()
{
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
if (!bw.IsBusy)
{
bw.RunWorkerAsync();
}
else
{
throw new InvalidOperationException("BackgroundWorker is busy");
}
}
private static void bw_DoWork(object sender, DoWorkEventArgs e)
{
// Time taking task
mre.Set();
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (!(e.Error == null))
{
this.lbl_status.Text = "Cannot proceed, Error occured";
appStatus = status.Error;
}
else
{
this.lbl_status.Text = "Good to go...";
appStatus = status.Success;
}
}
private void btn_login_Click(object sender, EventArgs e)
{
mre.WaitOne();
if(appStatus == status.Success)
{
// Proceed with intended work
}
else
{
// Pop-up error occurred
}
}
}
答案 0 :(得分:2)
e.Error具有从DoWork抛出的异常。如果您在DoWork中使用try / catch,则没有例外。