Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get TargetInvocationException with BackgroundWorker.ReportProgress?

I am working on a C# project where I have a Backgroundworker which does my "expensive work".

In my "DoWork" I want to report progress by "backgroundworker.ReportProgress(some int)". But when my program comes to the call "backgroundworker.ReportProgress(some int)" I get a "System.Reflection.TargetInvocationException".

How do I fix my problem?

private void btnGrap_Click(object sender, EventArgs e)
    {
        //some code
        ListsObject listsObject = new ListsObject(filePaths, enumList);
        progressBar1.Maximum = 100;//count;
        this.bgrndWorkerSearchMatches.RunWorkerAsync(listsObject);
     }

_DoWork:

private void backgroundWorkerSearchMatches_DoWork(object sender, DoWorkEventArgs e)
    {
        for (int i = 0; i < 100; i++)
        {
            bgrndWorkerSearchMatches.ReportProgress(i);
        }
     }

_ProcessChanged:

private void bgrndWorkerSearchMatches_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        //progressBar1.Value = e.ProgressPercentage;
    }

I found the answer:

I created the backgroundworker eventhandler with Visual Studio and did not know that I have to manually set:

bgrndWorkerSearchMatches.WorkerReportsProgress = true;
like image 442
scro Avatar asked Aug 21 '26 14:08

scro


1 Answers

A TargetInvocationException is thrown to wrap a different exception that was thrown by the method that was ultimately called.

Check the InnerException to find out what happened.

like image 73
SLaks Avatar answered Aug 23 '26 04:08

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!