我有一个相当复杂的程序,所以我不会在这里存储所有东西。下面是一个简化版本:C# - 后台工作人员?
class Report {
private BackgroundWorker worker;
public Report(BackgroundWorker bgWorker, /* other variables, etc */) {
// other initializations, etc
worker = bgWorker;
}
private void SomeCalculations() {
// In this function, I'm doing things which may cause fatal errors.
// Example: I'm connecting to a database. If the connection fails,
// I need to quit and have my background worker report the error
}
}
// In the GUI WinForm app:
// using statements, etc.
using Report;
namespace ReportingService {
public partial class ReportingService : Form {
// My background worker
BackgroundWorker theWorker = new BackgroundWorker() {
WorkerReportsProgress = true
};
// The progress changed event
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) {
// e.UserState and e.ProgressPercentage on some labels, etc.
}
// The do work event for the worker, runs the number crunching algorithms in SomeCalculations();
void worker_DoWork(object sender, DoWorkEventArgs e) {
Report aReport = e.Argument as Report;
aReport.SomeCalculations();
}
// The completed event, where all my trouble is. I don't know how to retrieve the error,
// or where it originates from.
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
// How, exactly, do I get this error message? Who provides it? How?
if (e.Error != null) {
MessageBox.Show("Error: " + (e.Error as Exception).ToString());
}
else if (e.Cancelled) {
MessageBox.Show("Canceled");
}
// operation succeeded
else {
MessageBox.Show("Success");
}
}
// Initialization of the forml, etc
public ReportingService() {
InitializeComponent();
theWorker.ProgressChanged += worker_ProgressChanged;
theWorker.DoWork += worker_DoWork;
theWorker.RunWorkerCompleted += worker_RunWorkerCompleted;
}
// A button that the user clicks to execute the number crunching algorithm
private void sumButton_Click(object sender, EventArgs e) {
Report myReport = new Report(theWorker, /* some other variables, etc */)
theWorker.RunWorkerAsync(myReport);
}
}
}
这里是我的逻辑,并请纠正我,如果我要对这个错误的方法:
我抽象类出来的GUI的,因为它是〜2000行和需要成为它自己的自我包含的对象。
我将后台工作者传入我的课程,以便我可以报告我的数字处理进度。
我不知道该怎么做是让后台工作人员知道我的课内发生了错误。为了使RunWorkerCompleted参数成为一个异常,我的try/catch块需要去哪里,我应该在catch块中做什么?
感谢您的帮助!
编辑:
我试过下面的东西来测试错误处理:
记住我破坏我的数据库连接字符串故意收到一条错误消息。
在我的班级我做的:
// My number crunching algorithm contained within my class calls a function which does this:
// try {
using (SqlConnection c = GetConnection()) { // note: I've corrupted the connection string on purpose
c.Open(); // I get the exception thrown here
using (SqlCommand queryCommand = new SqlCommand(query, c)) { /* Loop over query, etc. */ }
c.Close();
}
// } catch (Exception e) { }
1. 从我的理解,未处理的异常被强制转换为RunWorkerCompletedEventArgs
的Error
部分?当我尝试这一点,我得到如下:
// In my winform application I initialize my background worker with these events:
void gapBW_DoWork(object sender, DoWorkEventArgs e) {
Report aReport = e.Argument as Report;
Report.Initialize(); // takes ~1 minute, throws SQL exception
Report.GenerateData(); // takes around ~2 minutes, throws file IO exceptions
}
void gapBW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
if (e.Error != null) { // I can't get this to trigger, How does this error get set?
MessageBox.Show("Error: " + (e.Error as Exception).ToString());
}
else if (e.Cancelled) {
MessageBox.Show("Canceled: " + (e.Result).ToString());
}
else {
MessageBox.Show("Success");
}
}
Visual Studio的说,我的应用程序扼流圈c.Open()
与未处理的异常失败。
2. 当我把一个try/catch块在我的DoWork功能:
void gapBW_DoWork(object sender, DoWorkEventArgs e) {
try {
Report aReport = e.Argument as Report;
aReport.Initialize(); // throws SQL exceptions
aReport.GenerateData(); // throws IO file exceptions
}
catch (Exception except) {
e.Cancel = true;
e.Result = except.Message.ToString();
}
}
void gapBW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
if (e.Error != null) { // I can't get this to trigger, How does this error get set?
MessageBox.Show("Error: " + (e.Error as Exception).ToString());
}
else if (e.Cancelled) {
MessageBox.Show("Canceled: " + (e.Result).ToString());
}
else {
MessageBox.Show("Success");
}
}
我得到了TargetInvocationException
了未处理的Program.cs中的自动生成Application.Run(new ReportingService());
线。我在RunWorkerCompleted上放置了一个断点,并可以看到e.Cancelled = true,e.Error = null和e.UserState = null。 e.Cancelled中包含的信息仅仅是“操作已被取消”。我想我从e.Result的无效转换中收到TargetInvocationException
(因为它为空)。我想知道的是,e.Error是如何来的,e.Canceled没有包含任何有用的信息为什么的操作被取消了?
3. 当我试图从内部的DoWork对异常俘获设置e.Canceled = true;
,我设法触发我RunWorkerCompleted
功能else if (e.Cancelled) {
线。我以为这是保留给请求作业被取消的用户呢?我从根本上误解了后台工作人员的功能?
感谢大家的帮助,但这最终解决了我的问题。原来这个问题不是我对C#的误解,而是我对Visual Studio的误解。我养成了按F5运行我的程序的习惯,并认为当一个异常未处理时,程序会崩溃。我没有意识到你可以再次按下F5继续处理。 –
另外不要忘记按下F10,F11和Shift-F11的功能。 ;-)) – Oliver
也许看看[这个问题](http://stackoverflow.com/questions/1044460/unhandled-exceptions-in-backgroundworker/1044610#1044610)也帮助你了。 – Oliver