none
Help! Crossthread value not valid VSTO Excel 2003 Workbook project RRS feed

  • Question

  • Hi All - I have tried everything but cannot resolve this issue.

    I get the error message:

    Cross-thread operation not valid: Control 'Button1' accessed from a thread other than the thread it was created on. 

    with the following piece of simple code in a Visual Studios 2008, Excel 2003 VSTO workbook project.  I simply test multithreading using a button.  It fails on the bold line in the runWorkerCompleted procedure.

     

    Public Class Sheet1
    
    
      Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Me.Range("A1").Value = "Started test"
        Me.Button1.Enabled = False
        BackgroundWorker1.RunWorkerAsync()
      End Sub
    
    
    
      Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        Threading.Thread.Sleep(5000)
    
        Me.Range("A2").Value = "Finished sleeping"
      End Sub
    
    
    
    
      Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        Me.Range("A3").Value = "About to enable button in RunWorkerCompleted"
        <strong>Me.Button1.Enabled = True</strong>
        Me.Range("A4").Value = "All done successfully"
      End Sub
    End Class
    
    

    I have tried to disable the host provider (can't - already disabled) as well as reseting the button.checkThreadSafe... property to false - it won't let me!

    Anything at all - anyone with a similar problem?  Any workaround?


     


    Anton
    Friday, July 15, 2011 12:32 AM

Answers

All replies

  • I have found a work-around, but it is dodgy and I still need to understand why the background worker is not functioning properly.

    For those interested, the workaround is to write data to an excel cell from the backgroundworkercomleted event.  Then have a procedure in the sheet.change event that checks if this cell has changed to a particular value - if so, update the controls.  This works because the main gui thread performs the sheet.change event and therefore also the control update.  But as i said, it's a nasty work-around.

     

    If anyone has a proper solution, that would be good.

    thanks,

    anton


    Anton
    Friday, July 15, 2011 1:32 AM
  • Hello,

    There's no proper solution for this because object models in Office are not thread-safe, please see On using threads in managed Office extensions.


    Regards from Belarus (GMT + 2),

    Andrei Smolin
    Add-in Express Team Leader
    Friday, July 15, 2011 4:05 PM
  • Thanks Andrei - at least that will stop me searching for a solution.
    Anton
    Saturday, July 16, 2011 7:44 AM