?
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
Medium Priority
?
384 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 2000 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
Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

 

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

NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

Question has a verified solution.

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

This article surveys and compares options for encoding and decoding base64 data.  It includes source code in C++ as well as examples of how to use standard Windows API functions for these tasks. We'll look at the algorithms — how encoding and decodi…
What my article will show is if you ever had to do processing to a listbox without being able to just select all the items in it. My software Visual Studio 2008 crystal report v11 My issue was I wanted to add crystal report to a form and show…
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…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …

770 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