Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8770573
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T17:34:57+00:00 2026-06-13T17:34:57+00:00

I am writing some kind of a wrapper for WCF calls (using BackgroundWorker) to

  • 0

I am writing some kind of a wrapper for WCF calls (using BackgroundWorker) to keep GUI from freezing while the call is ongoing. It is working mostly as it should, but I have a problem with the BackgroundWorker when the WCF call is throwing an exception. If an exception occurs in DoWork, I am able to detect it in RunWorkCompleted, but rethrowing it to the GUI does not work. I have read numerous threads with people mentioning that this should work.

Code for the wrapper (notice that the WCF call is symbolized by an exception being thrown):

private void GetSomething(Action<IEnumerable<int>> completedAction)
{
    BackgroundWorker b = new BackgroundWorker();

    b.DoWork += (s, evt) => { throw new Exception(); evt.Result = new List<int> { 1, 2, 3 }; };

    b.RunWorkerCompleted += (s, evt) =>
    {
        if (evt.Error == null && completedAction != null)
        {
           completedAction((IEnumerable<int>)evt.Result);
        }
        else if(evt.Error != null)
        {
           throw evt.Error;
        }
    };

    b.RunWorkerAsync();
}

Invoking code in a Windows form:

private void button3_Click(object sender, EventArgs e)
{
    try
    {
        GetSomething(list =>
        {
           foreach (int i in list)
           {
              listView1.Items.Add(new ListViewItem(i.ToString()));
           }
        });
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

While debugging this, I get:

  1. “Exception of type ‘System.Exception’ was thrown” in DoWork
  2. “Exception of type ‘System.Exception’ was thrown” at throw evt.Error
  3. “TargetInvocationException was unhandled” at Application.Run(new Form1()) in the Main method

What am I doing wrong? I would like to catch the exception in the Windows form.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T17:34:58+00:00Added an answer on June 13, 2026 at 5:34 pm

    The event b.RunWorkerCompleted is where you should do the error handling. You can pass in an Action<Exception> to do the error handling like

    private void GetSomething(Action<IEnumerable<int>> completedAction, Action<Exception> exceptionAction)
    {
        BackgroundWorker b = new BackgroundWorker();
    
        b.DoWork += (s, evt) => { throw new Exception(); evt.Result = new List<int> { 1, 2, 3 }; };
    
        b.RunWorkerCompleted += (s, evt) =>
        {
            if (evt.Error == null && completedAction != null)
                completedAction((IEnumerable<int>)evt.Result);
            else if(evt.Error != null)
                exceptionAction(evt.Error);
        };
    
        b.RunWorkerAsync();
    }
    

    However this tends to get ugly. If you use .Net 4 or 4.5 you can resort to Tasks. The Task<TResult> was created for exactly that case:

    Task<IEnumerable<int>> GetSomething()
    {
        return Task.Factory.StartNew(() => { 
            Thread.Sleep(2000);
            throw new Exception(); 
            return (new List<int> { 1, 2, 3 }).AsEnumerable(); 
            });
    }
    

    Task basically is a signalling construct with

    • a .Result property
    • an .Exception property
    • a .ContinueWith() method

    Within ContinueWith() you can check if the Task in a faulted state (Exception got thrown).

    You can use it like

        private void button3_Click(object sender, EventArgs e)
        {
            GetSomething()
                .ContinueWith(task =>
                    {
                        if (task.IsCanceled)
                        {
                        }
                        else if (task.IsFaulted)
                        {
                            var ex = task.Exception.InnerException;
                            MessageBox.Show(ex.Message);
                        }
                        else if (task.IsCompleted)
                        {
                            var list = task.Result;
                            foreach (int i in list)
                            {
                                listView1.Items.Add(new ListViewItem(i.ToString()));
                            }
                        }
                    });
        }
    

    If you use .Net 4.5 and C#5 (you need VS2012 or VS2010 and the Async CTP) you can even resort to async and await like

        private async void button3_Click(object sender, EventArgs e)
        {
            try
            {
                var list = await GetSomething();
                foreach (int i in list)
                {
                    listView1.Items.Add(new ListViewItem(i.ToString()));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    

    … and all the magic is done by the compiler. Note that you can use try catch as you are used to.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm writing a program, some kind of database. While I was reading manual of
I'm writing an update program (using NSIS) and I want acquire some kind of
I'm using the DataContractSerializer to convert and object returned from a WCF call to
I am writing some kind of server application (in C++), which holds an fd_set
I am writing some kind of IPC functionality and need to pass certain resources
While writing some C code, I decided to compile it to assembly and read
While writing some views to respond to ajax requests i find it somewhat strange
So I was writing some queries today and was using top 10 on a
i'm writing some kind of application that will send http requests to server. My
I am writing some kind of search engine for my web application and i

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.