2011-08-18 252 views
4

我有一个相当复杂的程序,所以我不会在这里存储所有东西。下面是一个简化版本: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); 
     } 
    } 
} 

这里是我的逻辑,并请纠正我,如果我要对这个错误的方法:

  1. 我抽象类出来的GUI的,因为它是〜2000行和需要成为它自己的自我包含的对象。

  2. 我将后台工作者传入我的课程,以便我可以报告我的数字处理进度。

我不知道该怎么做是让后台工作人员知道我的课内发生了错误。为了使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. 从我的理解,未处理的异常被强制转换为RunWorkerCompletedEventArgsError部分?当我尝试这一点,我得到如下:

// 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) {线。我以为这是保留给请求作业被取消的用户呢?我从根本上误解了后台工作人员的功能?

回答

2

我想这个小测试程序,它按预期工作:

static void Main(string[] args) 
{ 
    var worker = new BackgroundWorker(); 

    worker.DoWork += (sender, e) => { throw new ArgumentException(); }; 
    worker.RunWorkerCompleted += (sender, e) => Console.WriteLine(e.Error.Message); 
    worker.RunWorkerAsync(); 

    Console.ReadKey(); 
} 

但是当我运行在调试器中这PROGRAMM我也得到了消息,关于在罚球语句未处理的异常。但我只是再次按下F5,并继续没有任何问题。

+0

感谢大家的帮助,但这最终解决了我的问题。原来这个问题不是我对C#的误解,而是我对Visual Studio的误解。我养成了按F5运行我的程序的习惯,并认为当一个异常未处理时,程序会崩溃。我没有意识到你可以再次按下F5继续处理。 –

+0

另外不要忘记按下F10,F11和Shift-F11的功能。 ;-)) – Oliver

+0

也许看看[这个问题](http://stackoverflow.com/questions/1044460/unhandled-exceptions-in-backgroundworker/1044610#1044610)也帮助你了。 – Oliver

1

如果发生任何错误,请在doEvent的catch块中设置e.Cancel = true。设置WorkerSupportsCancellation属性第一。

在DoWork事件中。

private void bw_DoWork(object sender, DoWorkEventArgs e) 
    { 
     try 
     { 
      if(!backgroundWorkder.CancellationPending) 
      { 
       // .... 
      } 
     } 
     catch 
     { 
      if (bgWorker.WorkerSupportsCancellation && !bWorker.CancellationPending) 
      { 
       e.Cancel = true; 
       e.Result = "Give your error"; 
       return; 
      } 
     } 
    } 

OnRunWorkerCompleted方法。

private void BW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
    { 

    if(e.Cancelled) 
     { 
      MessageBox.Show(e.Result.ToString()); 
      return; 
     } 
} 

如果您在DoEvent中没有执行任何异常处理。 BackgroundWorker自己为你做这个。

如果一个异常是一个异步操作过程中提出,类 将分配异常错误属性。在访问派生自 的类中的任何属性之前,客户端 应用程序的事件处理程序委托应检查错误属性 AsyncCompletedEventArgs;否则,该属性将引发一个 TargetInvocationException,其InnerException属性保留对Error的 引用。

如果操作被取消,Error属性的值为null。

在这种情况下。

private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
{ 
    // First, handle the case where an exception was thrown. 
    if (e.Error != null) 
    { 
     MessageBox.Show(e.Error.Message); 
    } 
    else if (e.Cancelled) 
    { 
     // Next, handle the case where the user canceled the operation.   
    } 
} 

有关更多详细信息,请参见here

2

你在正确的轨道上。在RunWorkerCompleted事件中,e.Error参数包含引发的任何异常。在这种情况下,你应该把你的

if (e.Error != null) {...} 

try您在运行您的后台工作的catch块,如果是有道理的。

+0

因此,我不需要围绕我的Report类中的SQL查询进行try/catch?当我删除它时,我得到一个SqlException是由用户代码错误未处理。除非我的工作人员的工作完成,否则这个例外是不会发生的? –

+1

如果您正在调试,只需按继续(默认情况下为F5),并且控件应该流入您的RunWorkerCompleted事件处理程序,并且应该填充e.Error。 – Thebigcheeze

0

每次DoWork中的操作完成,取消或抛出异常时,都会触发RunWorkerCompleted。然后在RunWorkerCompleted中检查RunWorkerCompletedEventArgs,如果Error不为null。当DoWork出现异常时,会自动设置错误属性。在这种特殊情况下无需尝试捕捉。

您正在正确的轨道上。