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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Pieter

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

    Hi,

    I'm having some weird problem using the BackGroundWorke r in an Outlook
    (2003) Add-In, with VB.NET 2005:
    I'm using the BackGroundWorke r 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.bgwInfoOutlo ok.RunWorkerAsy nc(Me.m_colItem s)

    Private Sub bgwInfoOutlook_ DoWork(ByVal sender As Object, ByVal e As
    System.Componen tModel.DoWorkEv entArgs) Handles bgwInfoOutlook. DoWork
    Dim col As Collection = e.Argument
    AddHandler docCtrl.InfoLis tChanged, AddressOf InfoListChanged
    Dim str As String = docCtrl.GetOutl ookInfo(col,
    Me.m_objOutlook Folder)
    e.Result = docCtrl.AddedDo cMails
    End Sub

    Private Sub InfoListChanged (ByVal sender As Object, ByVal e As
    EventArgs)
    Me.bgwInfoOutlo ok.ReportProgre ss(0)
    End Sub

    Private Sub bgwInfoOutlook_ ProgressChanged (ByVal sender As Object, ByVal
    e As System.Componen tModel.Progress ChangedEventArg s) Handles
    bgwInfoOutlook. ProgressChanged
    'bind the list to the datagridview
    Try
    Me.dgvAdd.DataS ource = Nothing
    Me.dgvAdd.DataS ource = docCtrl.InfoLis t
    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.InvalidO perationExcepti on: {"Cross-thread operation not valid:
    Control 'dgvAdd' accessed from a thread other than the thread it was created
    on."}
    Data: {System.Collect ions.ListDictio naryInternal}
    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.g et_Handle()
    at System.Windows. Forms.Control.g et_InternalHand le()
    at System.Windows. Forms.Control.g et_CreateParams ()
    at System.Windows. Forms.ScrollBar .get_CreatePara ms()
    at System.Windows. Forms.VScrollBa r.get_CreatePar ams()
    at System.Windows. Forms.Control.U pdateBounds(Int 32 x, Int32 y, Int32
    width, Int32 height)
    at System.Windows. Forms.Control.S etBoundsCore(In t32 x, Int32 y, Int32
    width, Int32 height, BoundsSpecified specified)
    at System.Windows. Forms.Control.S etBounds(Int32 x, Int32 y, Int32 width,
    Int32 height, BoundsSpecified specified)
    at System.Windows. Forms.Control.s et_Bounds(Recta ngle value)
    at System.Windows. Forms.DataGridV iew.LayoutScrol lBars()
    at System.Windows. Forms.DataGridV iew.ComputeLayo ut()
    at System.Windows. Forms.DataGridV iew.PerformLayo utPrivate(Boole an
    useRowShortcut, Boolean computeVisibleR ows, Boolean
    invalidInAdjust FillingColumns, Boolean repositionEditi ngControl)
    at
    System.Windows. Forms.DataGridV iew.OnColumnWid thChanged(DataG ridViewColumnEv entArgs
    e)
    at
    System.Windows. Forms.DataGridV iew.OnBandThick nessChanged(Dat aGridViewBand
    dataGridViewBan d)
    at System.Windows. Forms.DataGridV iewBand.set_Thi cknessInternal( Int32
    value)
    at System.Windows. Forms.DataGridV iew.AdjustFilli ngColumns()
    at System.Windows. Forms.DataGridV iew.ComputeLayo ut()
    at System.Windows. Forms.DataGridV iew.PerformLayo utPrivate(Boole an
    useRowShortcut, Boolean computeVisibleR ows, Boolean
    invalidInAdjust FillingColumns, Boolean repositionEditi ngControl)
    at System.Windows. Forms.DataGridV iew.ResetUIStat e(Boolean useRowShortcut,
    Boolean computeVisibleR ows)
    at
    System.Windows. Forms.DataGridV iewRowCollectio n.OnCollectionC hanged_PreNotif ication(Collect ionChangeAction
    cca, Int32 rowIndex, Int32 rowCount, DataGridViewRow & dataGridViewRow ,
    Boolean changeIsInserti on)
    at
    System.Windows. Forms.DataGridV iewRowCollectio n.OnCollectionC hanged(Collecti onChangeEventAr gs
    e, Int32 rowIndex, Int32 rowCount, Boolean changeIsDeletio n, Boolean
    changeIsInserti on, Boolean recreateNewRow, Point newCurrentCell)
    at System.Windows. Forms.DataGridV iewRowCollectio n.InsertInterna l(Int32
    rowIndex, DataGridViewRow dataGridViewRow , Boolean force)
    at
    System.Windows. Forms.DataGridV iew.DataGridVie wDataConnection .ProcessListCha nged(ListChange dEventArgs
    e)
    at
    System.Windows. Forms.DataGridV iew.DataGridVie wDataConnection .currencyManage r_ListChanged(O bject
    sender, ListChangedEven tArgs e)
    at
    System.Windows. Forms.CurrencyM anager.OnListCh anged(ListChang edEventArgs e)
    at System.Windows. Forms.CurrencyM anager.List_Lis tChanged(Object sender,
    ListChangedEven tArgs e)
    at System.Componen tModel.BindingL ist`1.OnListCha nged(ListChange dEventArgs
    e)
    at System.Componen tModel.BindingL ist`1.FireListC hanged(ListChan gedType
    type, Int32 index)
    at System.Componen tModel.BindingL ist`1.InsertIte m(Int32 index, T item)
    at System.Collecti ons.ObjectModel .Collection`1.A dd(T item)
    at BaseFramework.c lsBaseList`1.Ad d(T item) in D:\NET Projecten\Code
    Source Sodimex - Ghost\BaseFrame work\clsBaseLis t.vb:line 461
    at DocControl.clsD ocControl.GetOu tlookInfo(Colle ction colItems, Object
    oFolder, Boolean blnAttachments) in D:\NET Projecten\Code Source Sodimex -
    Ghost\DocContro l\Business Layer\clsDocCon trol.vb:line 597"
    TargetSite: {System.Reflect ion.RuntimeMeth odInfo}


  • Dmytro Lapshyn [MVP]

    #2
    Re: BackGroundWorke r.ProgressChang ed "Cross-thread operation not valid" at 2nd/3th/... progress

    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.

    "Pieter" <pietercoucke@h otmail.com> wrote in message
    news:eU5pe%23IM GHA.208@tk2msft ngp13.phx.gbl.. .[color=blue]
    > Hi,
    >
    > I'm having some weird problem using the BackGroundWorke r in an Outlook
    > (2003) Add-In, with VB.NET 2005:
    > I'm using the BackGroundWorke r 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.bgwInfoOutlo ok.RunWorkerAsy nc(Me.m_colItem s)
    >
    > Private Sub bgwInfoOutlook_ DoWork(ByVal sender As Object, ByVal e As
    > System.Componen tModel.DoWorkEv entArgs) Handles bgwInfoOutlook. DoWork
    > Dim col As Collection = e.Argument
    > AddHandler docCtrl.InfoLis tChanged, AddressOf InfoListChanged
    > Dim str As String = docCtrl.GetOutl ookInfo(col,
    > Me.m_objOutlook Folder)
    > e.Result = docCtrl.AddedDo cMails
    > End Sub
    >
    > Private Sub InfoListChanged (ByVal sender As Object, ByVal e As
    > EventArgs)
    > Me.bgwInfoOutlo ok.ReportProgre ss(0)
    > End Sub
    >
    > Private Sub bgwInfoOutlook_ ProgressChanged (ByVal sender As Object,
    > ByVal e As System.Componen tModel.Progress ChangedEventArg s) Handles
    > bgwInfoOutlook. ProgressChanged
    > 'bind the list to the datagridview
    > Try
    > Me.dgvAdd.DataS ource = Nothing
    > Me.dgvAdd.DataS ource = docCtrl.InfoLis t
    > 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.InvalidO perationExcepti on: {"Cross-thread operation not valid:
    > Control 'dgvAdd' accessed from a thread other than the thread it was
    > created on."}
    > Data: {System.Collect ions.ListDictio naryInternal}
    > 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.g et_Handle()
    > at System.Windows. Forms.Control.g et_InternalHand le()
    > at System.Windows. Forms.Control.g et_CreateParams ()
    > at System.Windows. Forms.ScrollBar .get_CreatePara ms()
    > at System.Windows. Forms.VScrollBa r.get_CreatePar ams()
    > at System.Windows. Forms.Control.U pdateBounds(Int 32 x, Int32 y, Int32
    > width, Int32 height)
    > at System.Windows. Forms.Control.S etBoundsCore(In t32 x, Int32 y, Int32
    > width, Int32 height, BoundsSpecified specified)
    > at System.Windows. Forms.Control.S etBounds(Int32 x, Int32 y, Int32 width,
    > Int32 height, BoundsSpecified specified)
    > at System.Windows. Forms.Control.s et_Bounds(Recta ngle value)
    > at System.Windows. Forms.DataGridV iew.LayoutScrol lBars()
    > at System.Windows. Forms.DataGridV iew.ComputeLayo ut()
    > at System.Windows. Forms.DataGridV iew.PerformLayo utPrivate(Boole an
    > useRowShortcut, Boolean computeVisibleR ows, Boolean
    > invalidInAdjust FillingColumns, Boolean repositionEditi ngControl)
    > at
    > System.Windows. Forms.DataGridV iew.OnColumnWid thChanged(DataG ridViewColumnEv entArgs
    > e)
    > at
    > System.Windows. Forms.DataGridV iew.OnBandThick nessChanged(Dat aGridViewBand
    > dataGridViewBan d)
    > at System.Windows. Forms.DataGridV iewBand.set_Thi cknessInternal( Int32
    > value)
    > at System.Windows. Forms.DataGridV iew.AdjustFilli ngColumns()
    > at System.Windows. Forms.DataGridV iew.ComputeLayo ut()
    > at System.Windows. Forms.DataGridV iew.PerformLayo utPrivate(Boole an
    > useRowShortcut, Boolean computeVisibleR ows, Boolean
    > invalidInAdjust FillingColumns, Boolean repositionEditi ngControl)
    > at System.Windows. Forms.DataGridV iew.ResetUIStat e(Boolean
    > useRowShortcut, Boolean computeVisibleR ows)
    > at
    > System.Windows. Forms.DataGridV iewRowCollectio n.OnCollectionC hanged_PreNotif ication(Collect ionChangeAction
    > cca, Int32 rowIndex, Int32 rowCount, DataGridViewRow & dataGridViewRow ,
    > Boolean changeIsInserti on)
    > at
    > System.Windows. Forms.DataGridV iewRowCollectio n.OnCollectionC hanged(Collecti onChangeEventAr gs
    > e, Int32 rowIndex, Int32 rowCount, Boolean changeIsDeletio n, Boolean
    > changeIsInserti on, Boolean recreateNewRow, Point newCurrentCell)
    > at System.Windows. Forms.DataGridV iewRowCollectio n.InsertInterna l(Int32
    > rowIndex, DataGridViewRow dataGridViewRow , Boolean force)
    > at
    > System.Windows. Forms.DataGridV iew.DataGridVie wDataConnection .ProcessListCha nged(ListChange dEventArgs
    > e)
    > at
    > System.Windows. Forms.DataGridV iew.DataGridVie wDataConnection .currencyManage r_ListChanged(O bject
    > sender, ListChangedEven tArgs e)
    > at
    > System.Windows. Forms.CurrencyM anager.OnListCh anged(ListChang edEventArgs e)
    > at System.Windows. Forms.CurrencyM anager.List_Lis tChanged(Object sender,
    > ListChangedEven tArgs e)
    > at
    > System.Componen tModel.BindingL ist`1.OnListCha nged(ListChange dEventArgs e)
    > at System.Componen tModel.BindingL ist`1.FireListC hanged(ListChan gedType
    > type, Int32 index)
    > at System.Componen tModel.BindingL ist`1.InsertIte m(Int32 index, T item)
    > at System.Collecti ons.ObjectModel .Collection`1.A dd(T item)
    > at BaseFramework.c lsBaseList`1.Ad d(T item) in D:\NET Projecten\Code
    > Source Sodimex - Ghost\BaseFrame work\clsBaseLis t.vb:line 461
    > at DocControl.clsD ocControl.GetOu tlookInfo(Colle ction colItems, Object
    > oFolder, Boolean blnAttachments) in D:\NET Projecten\Code Source Sodimex -
    > Ghost\DocContro l\Business Layer\clsDocCon trol.vb:line 597"
    > TargetSite: {System.Reflect ion.RuntimeMeth odInfo}
    >
    >[/color]


    Comment

    • Pieter

      #3
      Re: BackGroundWorke r.ProgressChang ed &quot;Cross-thread operation not valid&quot; at 2nd/3th/... progress

      Hi,

      I've tryed it, but it didn't work either :-/
      And isn't the BackGroundWorke r 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.Componen tModel.Progress ChangedEventArg s) Handles
      bgwInfoOutlook. ProgressChanged
      Try
      SetDataSource()
      Catch ex As Exception
      ErrorMessage(ex )
      End Try
      End Sub

      Delegate Sub SetDgvCallback( )

      Private Sub SetDataSource()
      If Me.dgvAdd.Invok eRequired Then
      Dim d As New SetDgvCallback( AddressOf SetDataSource)
      Me.Invoke(d, Nothing)
      Else
      Me.dgvAdd.DataS ource = Nothing
      Me.dgvAdd.DataS ource = docCtrl.InfoLis t
      End If
      End Sub

      And the werit thing is: the Me.dgvAdd.Invok eRequired returns False...

      "Dmytro Lapshyn [MVP]" <x-code@no-spam-please.hotpop.c om> wrote in message
      news:%23JRvllJM GHA.1536@TK2MSF TNGP11.phx.gbl. ..[color=blue]
      > 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.[/color]


      Comment

      • Josh Einstein

        #4
        Re: BackGroundWorke r.ProgressChang ed &quot;Cross-thread operation not valid&quot; at 2nd/3th/... progress

        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



        "Pieter" <pietercoucke@h otmail.com> wrote in message
        news:uOMzr6JMGH A.3104@TK2MSFTN GP11.phx.gbl...[color=blue]
        > Hi,
        >
        > I've tryed it, but it didn't work either :-/
        > And isn't the BackGroundWorke r 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.Componen tModel.Progress ChangedEventArg s) Handles
        > bgwInfoOutlook. ProgressChanged
        > Try
        > SetDataSource()
        > Catch ex As Exception
        > ErrorMessage(ex )
        > End Try
        > End Sub
        >
        > Delegate Sub SetDgvCallback( )
        >
        > Private Sub SetDataSource()
        > If Me.dgvAdd.Invok eRequired Then
        > Dim d As New SetDgvCallback( AddressOf SetDataSource)
        > Me.Invoke(d, Nothing)
        > Else
        > Me.dgvAdd.DataS ource = Nothing
        > Me.dgvAdd.DataS ource = docCtrl.InfoLis t
        > End If
        > End Sub
        >
        > And the werit thing is: the Me.dgvAdd.Invok eRequired returns False...
        >
        > "Dmytro Lapshyn [MVP]" <x-code@no-spam-please.hotpop.c om> wrote in message
        > news:%23JRvllJM GHA.1536@TK2MSF TNGP11.phx.gbl. ..[color=green]
        >> 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.[/color]
        >
        >[/color]


        Comment

        • Josh Einstein

          #5
          Re: BackGroundWorke r.ProgressChang ed &quot;Cross-thread operation not valid&quot; at 2nd/3th/... progress

          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 RunWorkerComple ted.

          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



          "Pieter" <pietercoucke@h otmail.com> wrote in message
          news:uOMzr6JMGH A.3104@TK2MSFTN GP11.phx.gbl...[color=blue]
          > Hi,
          >
          > I've tryed it, but it didn't work either :-/
          > And isn't the BackGroundWorke r 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.Componen tModel.Progress ChangedEventArg s) Handles
          > bgwInfoOutlook. ProgressChanged
          > Try
          > SetDataSource()
          > Catch ex As Exception
          > ErrorMessage(ex )
          > End Try
          > End Sub
          >
          > Delegate Sub SetDgvCallback( )
          >
          > Private Sub SetDataSource()
          > If Me.dgvAdd.Invok eRequired Then
          > Dim d As New SetDgvCallback( AddressOf SetDataSource)
          > Me.Invoke(d, Nothing)
          > Else
          > Me.dgvAdd.DataS ource = Nothing
          > Me.dgvAdd.DataS ource = docCtrl.InfoLis t
          > End If
          > End Sub
          >
          > And the werit thing is: the Me.dgvAdd.Invok eRequired returns False...
          >
          > "Dmytro Lapshyn [MVP]" <x-code@no-spam-please.hotpop.c om> wrote in message
          > news:%23JRvllJM GHA.1536@TK2MSF TNGP11.phx.gbl. ..[color=green]
          >> 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.[/color]
          >
          >[/color]


          Comment

          • Pieter

            #6
            Re: BackGroundWorke r.ProgressChang ed &quot;Cross-thread operation not valid&quot; at 2nd/3th/... progress

            "Josh Einstein" <josheinstein@h otmail.com> wrote in message
            news:OW9bQaLMGH A.2580@TK2MSFTN GP14.phx.gbl...
            [color=blue]
            > 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.[/color]

            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...



            Comment

            • Dmitry Streblechenko

              #7
              Re: BackGroundWorke r.ProgressChang ed &quot;Cross-thread operation not valid&quot; at 2nd/3th/... progress

              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)
              mapi,cdo,outlook,cdonts,cdoex,IAddrBook,IAttach,IDistList,IMAPIContainer,IMAPIFolder,IMAPIProp,IMAPISession,IMAPIStatus,IMAPI,Table,IMailUser,IMessage,IMsgStore,ThisOutlookSession,calendarview,cdoitem,cdolive,cdowf,hiddenmessages,ifolder,imapifolder,imapiprop,imessage,infostore,infostores,iprofadmin,logonsmtp,mailitem,mapifolder,mapiobject,meetingitem,meetingitems,messagefilter,messagestore,messageview,objectrenderer,officevba,outlookspy,rawtable,recurrencetype,storeid,tableview,Active Messaging,Exchange Server Scripting,attachment object,calendarview,cdosession,collaboration data,entryid,extended,global address list,messaging api,outbox,inbox,outlooktoday,vb,vba,basic,visual basic,delphi,vc,script

              OutlookSpy - Outlook, CDO
              and MAPI Developer Tool

              "Josh Einstein" <josheinstein@h otmail.com> wrote in message
              news:ORPmFXLMGH A.1180@TK2MSFTN GP09.phx.gbl...[color=blue]
              > 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
              >
              >
              > "Pieter" <pietercoucke@h otmail.com> wrote in message
              > news:uOMzr6JMGH A.3104@TK2MSFTN GP11.phx.gbl...[color=green]
              >> Hi,
              >>
              >> I've tryed it, but it didn't work either :-/
              >> And isn't the BackGroundWorke r 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.Componen tModel.Progress ChangedEventArg s) Handles
              >> bgwInfoOutlook. ProgressChanged
              >> Try
              >> SetDataSource()
              >> Catch ex As Exception
              >> ErrorMessage(ex )
              >> End Try
              >> End Sub
              >>
              >> Delegate Sub SetDgvCallback( )
              >>
              >> Private Sub SetDataSource()
              >> If Me.dgvAdd.Invok eRequired Then
              >> Dim d As New SetDgvCallback( AddressOf SetDataSource)
              >> Me.Invoke(d, Nothing)
              >> Else
              >> Me.dgvAdd.DataS ource = Nothing
              >> Me.dgvAdd.DataS ource = docCtrl.InfoLis t
              >> End If
              >> End Sub
              >>
              >> And the werit thing is: the Me.dgvAdd.Invok eRequired returns False...
              >>
              >> "Dmytro Lapshyn [MVP]" <x-code@no-spam-please.hotpop.c om> wrote in
              >> message news:%23JRvllJM GHA.1536@TK2MSF TNGP11.phx.gbl. ..[color=darkred]
              >>> 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.[/color]
              >>
              >>[/color]
              >
              >[/color]


              Comment

              • Josh Einstein

                #8
                Re: BackGroundWorke r.ProgressChang ed &quot;Cross-thread operation not valid&quot; at 2nd/3th/... progress

                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 RunWorkerComple ted 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



                "Pieter" <pietercoucke@h otmail.com> wrote in message
                news:O0cG$fLMGH A.3556@TK2MSFTN GP10.phx.gbl...[color=blue]
                > "Josh Einstein" <josheinstein@h otmail.com> wrote in message
                > news:OW9bQaLMGH A.2580@TK2MSFTN GP14.phx.gbl...
                >[color=green]
                >> 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.[/color]
                >
                > 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...
                >
                >
                >[/color]


                Comment

                • Josh Einstein

                  #9
                  Re: BackGroundWorke r.ProgressChang ed &quot;Cross-thread operation not valid&quot; at 2nd/3th/... progress

                  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



                  "Dmitry Streblechenko" <dmitry@dimastr .com> wrote in message
                  news:O8i9G0LMGH A.3984@TK2MSFTN GP14.phx.gbl...[color=blue]
                  > 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
                  >
                  > "Josh Einstein" <josheinstein@h otmail.com> wrote in message
                  > news:ORPmFXLMGH A.1180@TK2MSFTN GP09.phx.gbl...[color=green]
                  >> 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
                  >>
                  >>
                  >> "Pieter" <pietercoucke@h otmail.com> wrote in message
                  >> news:uOMzr6JMGH A.3104@TK2MSFTN GP11.phx.gbl...[color=darkred]
                  >>> Hi,
                  >>>
                  >>> I've tryed it, but it didn't work either :-/
                  >>> And isn't the BackGroundWorke r 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.Componen tModel.Progress ChangedEventArg s) Handles
                  >>> bgwInfoOutlook. ProgressChanged
                  >>> Try
                  >>> SetDataSource()
                  >>> Catch ex As Exception
                  >>> ErrorMessage(ex )
                  >>> End Try
                  >>> End Sub
                  >>>
                  >>> Delegate Sub SetDgvCallback( )
                  >>>
                  >>> Private Sub SetDataSource()
                  >>> If Me.dgvAdd.Invok eRequired Then
                  >>> Dim d As New SetDgvCallback( AddressOf SetDataSource)
                  >>> Me.Invoke(d, Nothing)
                  >>> Else
                  >>> Me.dgvAdd.DataS ource = Nothing
                  >>> Me.dgvAdd.DataS ource = docCtrl.InfoLis t
                  >>> End If
                  >>> End Sub
                  >>>
                  >>> And the werit thing is: the Me.dgvAdd.Invok eRequired returns False...
                  >>>
                  >>> "Dmytro Lapshyn [MVP]" <x-code@no-spam-please.hotpop.c om> wrote in
                  >>> message news:%23JRvllJM GHA.1536@TK2MSF TNGP11.phx.gbl. ..
                  >>>> 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.
                  >>>
                  >>>[/color]
                  >>
                  >>[/color]
                  >
                  >[/color]


                  Comment

                  Working...