Solved

How do I retuen Exception from a method that has been called from Backgroundworker bgw_DoWork event and how do I correctly execute Cancel Event of BackgroundWorker ?

Posted on 2011-09-28
7
382 Views
Last Modified: 2013-11-12
I am trying to implement a Backgroundworker . This worker will call one of my methods that do lots of file processing as well as db processing.  Name of the method is LoadASpreadSheet(), which is getting called from background worker DoWoker event. However it is not returning the catch exceptions. At present this method is void but I can return a string or anything else. Basically I need to assign the return value from LoadASpreadSheet() to e.Result at bkg_Dowork event right?

So question is how do I implement this into  LoadASpreadSheet()
catch (Exception eX)
{
      eX.Result ; ??
       or
      eX.GetType ; ??
     etc
                    
 }

Open in new window


I need to return the catch Exception from this method ...please help me.

Here is my class in short
namesapace ...
{

   public partial class MyClass1 : System.Windows.window
   {
        InitializeComponent();
        ConfigureBackgroundWorker();
   }

   void ConfigureBackgroundWorker()
{
    bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
    bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
    bgw.WorkerSupportsCancellation = true;
}

void StartBackgroundWorker()
{
    if(!bgw.IsBusy)
        bgw.RunWorkerAsync();
}

void CancelBackgroundWorker()
{
    if (bgw != null && bgw.IsBusy && bgw.WorkerSupportsCancellation && !bgw.CancellationPending)
        bgw.CancelAsync();
}

void bgw_DoWork(object sender, DoWorkEventArgs e)
{
    LoadASpreadSheet();
   if (bgw.CancellationPending)
        return;
}

void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
   
    if (e.Error != null)
    {
       string msgErr;
       msgErr = String.Concat(msgErr, e.Error.Message);
       msgErr = String.Concat(msgErr, e.Error.Source);
       errorBlock.Text = msgErr;
    }
    else if (e.Cancelled)
    {
        //LoadASpreadSheet() processing was cancelled
    }
    else
    {
        //Do whatever is needed after LoadASpreadSheet() has completed.
    }
}

..

Open in new window


LoadASpreadSheet() method is implemented in the above class.

I have start pb and on click event I call StartBackgroundWorker();
I do have a cancel pb and on cancel click event it call CancelBackgroundWorker() so user can stop current thread or process.

Right now is not working correctly.
Therefore two main issues First: how do I return the exception from
LoadASpreadSheet() method into DoWorker event?


LoadASpreadSheet() called two other method that I mentioned you before and one of this method does talk to database to do delete /insert operation via stored proc etc. Delete/Insert takes place in a transaction and in case of error this method catch it too. However I don't think that should be any issues.

Second: Why CancelBackgroundWorker() is not working?

Please get back to me I need to implement this today.

Regards,
Jedi


0
Comment
Question by:WantToBe_JediIT
  • 4
  • 3
7 Comments
 

Author Comment

by:WantToBe_JediIT
ID: 36813057
Please help me to solve this problem for BackgroundWorker Thread.

Thank you very much.

Jedi
0
 
LVL 8

Accepted Solution

by:
jagrut_patel earned 500 total points
ID: 36813117
Regarding Exception
----------------------------------
First make it clear whether you want to "throw" an exception or "return" an exception.

To return anything from LoadASpreadSheet() instead of void this method should have return type like string.
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
   e.Result = LoadASpreadSheet();
   if (bgw.CancellationPending)
        return;
}

string LoadASpreadSheet()
{
     try
    {
    }
    catch(Exception e1)
    {
       return e1.Message;
    }
}

Open in new window


Other way is as I showed in comment ID "36714787" at http://www.experts-exchange.com/Microsoft/Development/Microsoft_Programming/WPF_and_Silverlight/Q_27343200.html?cid=1572#a36812996


Regarding Cancelling BGW
---------------------------------
In LoadASpreadSheet you need to put code like,

//Intermittently check whether user requested cancellation. If so then cancel further processing.
if (bgw.CancellationPending)
   return;

This code can be placed "mutiple times" before/after each logically atomic operations. Like before operations like before opening a file, before making a database call, etc.

Remember that cancellation request is asynchronous. Meaning BGW will not automatically cancel the thread it is running. It is just an indication (CancellationPending becomes true) to your DoWork method that user has requested cancellation. It is developer's job to put code to actually stop processing of the asynchronously running operation.

For e.g. CancelAsync will not automatically cancel already invoked database operation. After database call returns we should check whether CancellationPending == true and if so gracefully stop further processing.

So in the LoadASpreadSheet you will need to periodically check whether CancellationPending is true and if so take steps to gracefully return. Gracefully means say you find that CancellationPending is true after opening a file then before returning you must close the file. Please read this carefully.

You need to decide at what stage(s) cancellation of asynhronous operation is possible. Cancellation will not automatically ROLLBACK already committed database changes. It will not close an already open file.
0
 

Author Comment

by:WantToBe_JediIT
ID: 36813292

Thank you very much and nice explanation. I would like to  "return" an exception from LoadASpreadSheet().  I understand that method needs to have a correct return type. However I have implemented code in LoadASpreadSheet() method which check for bad data in Excel sheet hence I do this

catch (Exception e)
{
      string msg = "Wrong Sets of rows"
}

or 
catch (Exception myEx)
{
                    String msg;
                    msg="Error: ";
                    msg= String.Concat(errorMessage, myEx.Message);
                    msg= String.Concat(errorMessage, " Line of : ");
                    msg= String.Concat(errorMessage, myEx.Source);
}

Open in new window


Could you please tell me howbgw_ RunWorkerCompleted() will handle this message or exception ? I know its ck for following
if (e.Error != null)
    {
       //error
    }
    else if (e.Cancelled)
    {
        //LoadASpreadSheet() processing was cancelled
    }
    else
    {
        //Do whatever is needed after LoadASpreadSheet() has completed.
    }

Open in new window


Therefore bgw_ RunWorkerCompleted()  will consider those exception  "return"  from LoadASpreadSheet() as error? I have doubt could you please explain.

Because those return exception from LoadASpreadSheet() should go only (if (e.Error != null) {})
 block of code of bgw_ RunWorkerCompleted()  .

Regards,

Jedi
0
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 

Author Comment

by:WantToBe_JediIT
ID: 36813509
I am waiting to hear from you, please write me.

Thank you.

Regards

Jedi
0
 
LVL 8

Expert Comment

by:jagrut_patel
ID: 36813551
See, you are not doing any special handling in catch() blocks that you placed in LoadASpreadSheet. You are simply formatting the exception message. Correct?

If yes then why are you not considering the option I already gave you twice.

Comment ID "36714787" at http://www.experts-exchange.com/Microsoft/Development/Microsoft_Programming/WPF_and_Silverlight/Q_27343200.html?cid=1572#a36812996


With this approach e.Error != null will be true in RunWorkerCompleted

Haven't you tried this or is it not understood or is it not useful?
0
 

Author Comment

by:WantToBe_JediIT
ID: 36813607
You mean this pattern in LoadASpreadSheet()

try
{
  //your current code
}
finally
{
  //your current code. 
}


Now in event-handler of RunWorkerCompleted do this

if(e.Error != null)
{
    String errorMessage;
    errorMessage ="Error: ";
    errorMessage = String.Concat(errorMessage, e.Error.Message);
    errorMessage = String.Concat(errorMessage, " Line: ");
    errorMessage = String.Concat(errorMessage, e.Error.Source);
    textBox1.Text= errorMessage;
}

Open in new window


So no catch at all in LoadASpreadSheet() ?

I change this method to return string type

However I get error from the following lines of code in LoadASpreadSheet() during compilation

if (bgw.CancellationPending)
        return;

Open in new window


error is "An object of a type convertible to 'string' is required. However solution is build and I run the  program.

How I can fix it please ??

Thanks
Jedi

0
 
LVL 8

Expert Comment

by:jagrut_patel
ID: 36813684
With this pattern no need to change return type of LoadASpreadSheet to string. Let it be void.

0

Featured Post

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This tutorial is about how to put some of your C++ program's functionality into a standard DLL, and how to make working with the EXE and the DLL simple and seamless.   We'll be using Microsoft Visual Studio 2008 and we will cut out the noise; that i…
This article describes a technique for converting RTF (Rich Text Format) data to HTML and provides C++ source that does it all in just a few lines of code. Although RTF is coming to be considered a "legacy" format, it is still in common use... po…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Finding and deleting duplicate (picture) files can be a time consuming task. My wife and I, our three kids and their families all share one dilemma: Managing our pictures. Between desktops, laptops, phones, tablets, and cameras; over the last decade…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question