在 BackgroundWorker 中:即使出现错误,RunWorkerCompleted 的 e.Error == null
In BackgroundWorker: RunWorkerCompleted's e.Error == null even in case of error
当我在我的时间任务周围放置 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
}
}
}
e.Error 有从 DoWork 抛出的异常。如果在DoWork内部使用try/catch,也不例外。
当我在我的时间任务周围放置 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
}
}
}
e.Error 有从 DoWork 抛出的异常。如果在DoWork内部使用try/catch,也不例外。