Hi Guys,
In my appplication Backgroundworker throw an error exception has been thrown by the target of an invocation.

Any idea how i can resolve this thread.

Dani AI

Generated

Quick expert summary and safe fix notes. The error "Exception has been thrown by the target of an invocation" is the System.Reflection.TargetInvocationException wrapper you see when an invoked delegate throws — in BackgroundWorker scenarios that usually means either (a) your worker thread touched WinForms controls directly, or (b) the invoked code threw an exception that got rethrown by Invoke. is correct: marshal UI work back to the UI thread. Do not use CheckForIllegalCrossThreadCalls = False (as tried) — that only hides race conditions and unpredictable failures.

Practical, reliable patterns:

  • Read any control values on the UI thread before starting the worker and pass them with RunWorkerAsync.
  • Use WorkerReportsProgress = True and ReportProgress for frequent UI updates; handle those updates in ProgressChanged.
  • Return final data via e.Result and update the UI in RunWorkerCompleted.
  • Wrap long-work code in Try/Catch; exceptions thrown in DoWork surface as e.Error in RunWorkerCompleted (inspect e.Error.InnerException if present).

Example patterns (not a duplicate of earlier code):

' capture UI then start
Dim inputText As String = TextBox1.Text
BGW.WorkerReportsProgress = True
BGW.RunWorkerAsync(inputText)
' in DoWork: get argument, call ReportProgress, set e.Result
Dim arg = CType(e.Argument, String)
CType(sender, BackgroundWorker).ReportProgress(0, "status")
e.Result = finalValue

If you still see the TargetInvocationException, inspect the inner exception/message in e.Error (or the invoked delegate's exception) to find the real cause. For new projects prefer Task/IProgress or async/await patterns, which give clearer control over synchronization.

Recommended Answers

All 6 Replies

Yes, this exception get raised if you try to access your controls from the backgroundworker. You can only access the controls from the thread, they were created on (so, the main thread)

Hope the following example will explain it better:

Imports System.ComponentModel

Public Class BGW

	Dim BGW As BackgroundWorker
	Private Sub btnStart_Click(sender As System.Object, e As System.EventArgs) Handles btnStart.Click
		BGW = New BackgroundWorker
		With BGW
			.WorkerSupportsCancellation = True
			AddHandler .DoWork, AddressOf BGW_DoWork
			AddHandler .RunWorkerCompleted, AddressOf BGW_Comnpleted
			.RunWorkerAsync()
		End With
	End Sub

	Private Sub btnStop_Click(sender As Object, e As System.EventArgs) Handles btnStop.Click
		BGW.CancelAsync()
	End Sub

	Private Sub BGW_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
		While Not BGW.CancellationPending
			'invoke to access controls
			Me.Invoke(Sub()
						  Label1.Text = Date.Now.ToString
					  End Sub)
			Threading.Thread.Sleep(1000)
		End While
	End Sub

	Private Sub BGW_Comnpleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
		Label1.Text = "BGW Completed" 'no invoke needed, as BGW thread is finished
	End Sub


End Class

Hi GeekByChoiCe,
For accessing controls from the backgroundworker used below code at form load it works for another forms where i used backgroundworker.

CheckForIllegalCrossThreadCalls = False

Using CheckForIllegalCrossThreadCalls = False is not recommended, especially if you need some values of your controls during your backround work.

So imagine you need the TextBox1.Text inside your thread and since you can NOT access this control from your thread, the value of Textbox1.Text will be NOTHING. which will then raise an error if you try in example to work with the text, since the text is nothing.

Please step off from CheckForIllegalCrossThreadCalls = false. else you will have ALWAYS unexpected results.

Hi GeekByChoiCe,
This line of code not working .....

Me.Invoke(Sub()
						  Label1.Text = Date.Now.ToString
					  End Sub)

Yeah sorry, seems this only works in VS2010 + .NET 4.0
So here a VS2008 version:

Imports System.ComponentModel

Public Class BGW

	Dim BGW As BackgroundWorker
	Private Delegate Sub myDelegate(txt As String) 'create a delegate

	Private Sub btnStart_Click(sender As System.Object, e As System.EventArgs) Handles btnStart.Click
		BGW = New BackgroundWorker
		With BGW
			.WorkerSupportsCancellation = True
			AddHandler .DoWork, AddressOf BGW_DoWork
			AddHandler .RunWorkerCompleted, AddressOf BGW_Comnpleted
			.RunWorkerAsync()
		End With
	End Sub

	Private Sub btnStop_Click(sender As Object, e As System.EventArgs) Handles btnStop.Click
		BGW.CancelAsync()
	End Sub

	Private Sub UpdateText(ByVal txt As String)	'address of the delegate
		Label1.Text = Date.Now.ToString
	End Sub
	Private Sub BGW_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
		While Not BGW.CancellationPending
			Me.Invoke(New myDelegate(AddressOf UpdateText), Date.Now.ToString) 'init the delegate and hand over the text to invoke
			Threading.Thread.Sleep(1000)
		End While
	End Sub

	Private Sub BGW_Comnpleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
		Label1.Text = "BGW Completed" 'no invoke needed, as BGW thread is finished
	End Sub

End Class

Thanks GeekByChoiCe its wonderfull solution....
Its working fine.:cool:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.