BackGroundWorker.ProgressChanged "Cross-thread operation not valid" at 2nd/3th/... progress

P

Pieter

Hi,

I'm having some weird problem using the BackGroundWorker in an Outlook
(2003) Add-In, with VB.NET 2005:
I'm using the BackGroundWorker to get the info of some mailitems, and after
each item I want to raise the ProgressChanged-event to update the
DataGridView.
It works fine when only one Progresschanged is fired, but at the second,
third, fopurth etc it raises everytile a 'Cross-thread operation not
valid"-exception on lmy DataGridView (dgvAdd).

Any idea what causes this problem? What am I doing wrong? What is the
problem here?

Any help our hints would be really appreciated!

Thanks a lot in advance,

Pieter


This is my code:
Me.bgwInfoOutlook.RunWorkerAsync(Me.m_colItems)

Private Sub bgwInfoOutlook_DoWork(ByVal sender As Object, ByVal e As
System.ComponentModel.DoWorkEventArgs) Handles bgwInfoOutlook.DoWork
Dim col As Collection = e.Argument
AddHandler docCtrl.InfoListChanged, AddressOf InfoListChanged
Dim str As String = docCtrl.GetOutlookInfo(col,
Me.m_objOutlookFolder)
e.Result = docCtrl.AddedDocMails
End Sub

Private Sub InfoListChanged(ByVal sender As Object, ByVal e As
EventArgs)
Me.bgwInfoOutlook.ReportProgress(0)
End Sub

Private Sub bgwInfoOutlook_ProgressChanged(ByVal sender As Object, ByVal
e As System.ComponentModel.ProgressChangedEventArgs) Handles
bgwInfoOutlook.ProgressChanged
'bind the list to the datagridview
Try
Me.dgvAdd.DataSource = Nothing
Me.dgvAdd.DataSource = docCtrl.InfoList
Catch ex As Exception
ErrorMessage(ex)
End Try
End Sub


This is the exception:

{"Cross-thread operation not valid: Control 'dgvAdd' accessed from a thread
other than the thread it was created on."}
System.InvalidOperationException: {"Cross-thread operation not valid:
Control 'dgvAdd' accessed from a thread other than the thread it was created
on."}
Data: {System.Collections.ListDictionaryInternal}
HelpLink: Nothing
InnerException: Nothing
Message: "Cross-thread operation not valid: Control 'dgvAdd' accessed
from a thread other than the thread it was created on."
Source: "System.Windows.Forms"
StackTrace: " at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Control.get_InternalHandle()
at System.Windows.Forms.Control.get_CreateParams()
at System.Windows.Forms.ScrollBar.get_CreateParams()
at System.Windows.Forms.VScrollBar.get_CreateParams()
at System.Windows.Forms.Control.UpdateBounds(Int32 x, Int32 y, Int32
width, Int32 height)
at System.Windows.Forms.Control.SetBoundsCore(Int32 x, Int32 y, Int32
width, Int32 height, BoundsSpecified specified)
at System.Windows.Forms.Control.SetBounds(Int32 x, Int32 y, Int32 width,
Int32 height, BoundsSpecified specified)
at System.Windows.Forms.Control.set_Bounds(Rectangle value)
at System.Windows.Forms.DataGridView.LayoutScrollBars()
at System.Windows.Forms.DataGridView.ComputeLayout()
at System.Windows.Forms.DataGridView.PerformLayoutPrivate(Boolean
useRowShortcut, Boolean computeVisibleRows, Boolean
invalidInAdjustFillingColumns, Boolean repositionEditingControl)
at
System.Windows.Forms.DataGridView.OnColumnWidthChanged(DataGridViewColumnEventArgs
e)
at
System.Windows.Forms.DataGridView.OnBandThicknessChanged(DataGridViewBand
dataGridViewBand)
at System.Windows.Forms.DataGridViewBand.set_ThicknessInternal(Int32
value)
at System.Windows.Forms.DataGridView.AdjustFillingColumns()
at System.Windows.Forms.DataGridView.ComputeLayout()
at System.Windows.Forms.DataGridView.PerformLayoutPrivate(Boolean
useRowShortcut, Boolean computeVisibleRows, Boolean
invalidInAdjustFillingColumns, Boolean repositionEditingControl)
at System.Windows.Forms.DataGridView.ResetUIState(Boolean useRowShortcut,
Boolean computeVisibleRows)
at
System.Windows.Forms.DataGridViewRowCollection.OnCollectionChanged_PreNotification(CollectionChangeAction
cca, Int32 rowIndex, Int32 rowCount, DataGridViewRow& dataGridViewRow,
Boolean changeIsInsertion)
at
System.Windows.Forms.DataGridViewRowCollection.OnCollectionChanged(CollectionChangeEventArgs
e, Int32 rowIndex, Int32 rowCount, Boolean changeIsDeletion, Boolean
changeIsInsertion, Boolean recreateNewRow, Point newCurrentCell)
at System.Windows.Forms.DataGridViewRowCollection.InsertInternal(Int32
rowIndex, DataGridViewRow dataGridViewRow, Boolean force)
at
System.Windows.Forms.DataGridView.DataGridViewDataConnection.ProcessListChanged(ListChangedEventArgs
e)
at
System.Windows.Forms.DataGridView.DataGridViewDataConnection.currencyManager_ListChanged(Object
sender, ListChangedEventArgs e)
at
System.Windows.Forms.CurrencyManager.OnListChanged(ListChangedEventArgs e)
at System.Windows.Forms.CurrencyManager.List_ListChanged(Object sender,
ListChangedEventArgs e)
at System.ComponentModel.BindingList`1.OnListChanged(ListChangedEventArgs
e)
at System.ComponentModel.BindingList`1.FireListChanged(ListChangedType
type, Int32 index)
at System.ComponentModel.BindingList`1.InsertItem(Int32 index, T item)
at System.Collections.ObjectModel.Collection`1.Add(T item)
at BaseFramework.clsBaseList`1.Add(T item) in D:\NET Projecten\Code
Source Sodimex - Ghost\BaseFramework\clsBaseList.vb:line 461
at DocControl.clsDocControl.GetOutlookInfo(Collection colItems, Object
oFolder, Boolean blnAttachments) in D:\NET Projecten\Code Source Sodimex -
Ghost\DocControl\Business Layer\clsDocControl.vb:line 597"
TargetSite: {System.Reflection.RuntimeMethodInfo}
 
D

Dmytro Lapshyn [MVP]

Hi Pieter,

As far as I know, .NET 2.0 strictly prohibits any access to the user
interface from background worker threads. This wasn't allowed in .NET 1.1
either, but in that version one sometimes could get away with violating the
rule. Now you'll get the "Cross-thread operation not valid" almost for sure.

Therefore, to do any updates to the UI properly, you should use the
Control.Invoke method to run the UI update code on the UI thread.
 
P

Pieter

Hi,

I've tryed it, but it didn't work either :-/
And isn't the BackGroundWorker designed so we shouldn't worry anymore about
those Invoke and Delegates-stuff?

This is my new code with Invoke, which doesn't work either... :-/

Private Sub bgwInfoOutlook_ProgressChanged(ByVal sender As Object, ByVal
e As System.ComponentModel.ProgressChangedEventArgs) Handles
bgwInfoOutlook.ProgressChanged
Try
SetDataSource()
Catch ex As Exception
ErrorMessage(ex)
End Try
End Sub

Delegate Sub SetDgvCallback()

Private Sub SetDataSource()
If Me.dgvAdd.InvokeRequired Then
Dim d As New SetDgvCallback(AddressOf SetDataSource)
Me.Invoke(d, Nothing)
Else
Me.dgvAdd.DataSource = Nothing
Me.dgvAdd.DataSource = docCtrl.InfoList
End If
End Sub

And the werit thing is: the Me.dgvAdd.InvokeRequired returns False...
 
J

Josh Einstein

The problem is more serious. You shouldn't be accessing any Outlook objects
from a background thread. It just won't work right and you'll have all sorts
of problems ranging from error messages to mysterious OUTLOOK.EXE processes
that won't shut down.

I'm afraid all of your communication with Outlook has to be done on the same
thread that calls your connect method. That would be the UI thread. The only
"async" methods you can use are the advanced search api's but I believe even
they are single-threaded much like a UI timer is.

--
Josh Einstein
Einstein Technologies
Microsoft Tablet PC MVP
Tablet Enhancements for Outlook 2.0 - Try it free for 14 days
www.tabletoutlook.com
 
J

Josh Einstein

Oh I should also mention that your error here doesn't have anything to do
with the cross-thread Outlook access but I would avoid that anyway.

Your error message here is the same thing Dmytro said about cross-thread UI
calls. Something you are doing in DoWork (which is in a background thread)
is modifying the data grid. You can't do any UI access in DoWork. Only in
ProgressChanged or RunWorkerCompleted.

But again, I would avoid accessing the Outlook API from a background thread.
It is not thread-safe and behaves unpredictably whether or not you employ
locking.

--
Josh Einstein
Einstein Technologies
Microsoft Tablet PC MVP
Tablet Enhancements for Outlook 2.0 - Try it free for 14 days
www.tabletoutlook.com
 
P

Pieter

Your error message here is the same thing Dmytro said about cross-thread
UI calls. Something you are doing in DoWork (which is in a background
thread) is modifying the data grid.

Well actually it isn't :-/
And I don't have the exception while the Dowork is performing its actions:
it happens when the ProgressChanged-event fires...
 
D

Dmitry Streblechenko

Why? COM in general (especially out-of-proc COM), and Outlook is particular
can handle cross thread/process calls just fine - all Outlook objects are
apartment threaded, so all calls will end up on the main Outlook thread
anyway.

Dmitry Streblechenko (MVP)
http://www.dimastr.com/
OutlookSpy - Outlook, CDO
and MAPI Developer Tool
 
J

Josh Einstein

You'll have to recheck your code. Set a breakpoint and look at the threads
window. You are definitely accessing the UI from the background thread
somewhere. ProgressChanged and RunWorkerCompleted are raised on the UI
thread. (Which is why InvokeRequired returns false.)

--
Josh Einstein
Einstein Technologies
Microsoft Tablet PC MVP
Tablet Enhancements for Outlook 2.0 - Try it free for 14 days
www.tabletoutlook.com
 
J

Josh Einstein

Well as we discussed in another thread, there are pumping and re-entrance
problems with the STA model. But, I don't claim to understand all of these.
What I do know however, is that if I change a line of code in my app that
accesses any of the Outlook API from a background thread, Outlook will fail
to shut down.

I can't speak for out of process, but in process (such as in the case of an
add in) exhibits this behavior for me. It's also one of the main reasons I
gave up on trying to use remoting in another project. And in my research
(sorry I don't have sources at the moment, it was over a year ago) I found
others were recommending to not do this either.

--
Josh Einstein
Einstein Technologies
Microsoft Tablet PC MVP
Tablet Enhancements for Outlook 2.0 - Try it free for 14 days
www.tabletoutlook.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top