none
Cross-thread operation not valid RRS feed

  • Question

  • Cross-thread operation not valid


    Hello,

    I am using Visual Studio 2010, MS Word 2007 Professional, .NET 4.0, C#.

    I have created a

    System.IO.FileSystemWatcher filewatcher = new FileSystemWatcher();

    object and then subscribed to it's created event.  In the created event, I have this:

    void filewatcher_Created(object sender, FileSystemEventArgs e)
            {
               ThisApplication.ActiveDocument.TrackRevisions = false;
               ThisApplication.Selection.WholeStory();
               // Other methods starting with ThisApplication.
            }

    When the above event is triggered, I get a Cross-thread operation not valid error.

    I know why I get this error.  It's because Word is running on a single thread. 
    I would like to know if anyone has a solution to get around this issue.
    Any help would be appreciated.

    Steve

     


    Steve
    Friday, September 16, 2011 7:39 PM

All replies

  • Hi,       

    If you have any control (form, panel...etc) created in main thread, you use that control and check if invoke is required.

    If you don't have any control than in Addin startup you can create control and get control handle:

     

    private Panel syncControl;
    
    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
         syncControl = new Panel();
         IntPtr ptrSyncControl = syncControl.Handle;
    }
    
    void filewatcher_Created(object sender, FileSystemEventArgs e)
    {
       if(syncControl.InvokeRequired)
       {
            syncControl.Invoke(new MethodInvoker(delegate
             {
               filewatcher_Created(sender, e)
             }));
       }
       else
       {
             ThisApplication.ActiveDocument.TrackRevisions = false;
             ThisApplication.Selection.WholeStory();
            // Other methods starting with ThisApplication.
       }       
    }
    


    • Proposed as answer by Adnan Dedic Friday, September 23, 2011 3:48 AM
    Saturday, September 17, 2011 10:44 AM
  • Hi Steve,

    How's the problem at your side now?  If you need any further assistance, please feel free to let me know.

    Good day!

    Thanks


    Michael Sun [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Friday, September 23, 2011 3:51 AM
    Moderator
  • Hello,

     

    Actually the solution above would work for controls but the FileWatcher is not a control.  I have instead redesigned my solution to not include a FileWatcher.


    Steve
    Friday, September 23, 2011 1:09 PM
  • Did you create FileWatcher in some Add-in or it is WinForm Application ?

    Friday, September 23, 2011 2:09 PM