2 Replies Latest reply on Mar 18, 2013 11:10 AM by Robin Staes

    C# Solidworks crash: Control 'button1' accessed from a thread other than the thread it was created on.

    Robin Staes

      Hello, when I have or had a document open solidworks crashes when I turn on my add in again.

       

      This is the error visual studio 2010 gives me:

      • An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
      • Additional information: Cross-thread operation not valid: Control 'button1' accessed from a thread other than the thread it was created on.

       

      This is the code which visual studio highlights:

       

      • public void UISetup()
      •         {
      •             mTaskpaneView = mSWApplication.CreateTaskpaneView2(Assembly.GetExecutingAssembly().Location.Replace(".dll", ".bmp"), "Solidworks <-> Isah Koppeling");
      •                 mTaskpaneHost = (KoppelingTaskpane)mTaskpaneView.AddControl(KoppelingTaskpane.SWTASKPANE_PROGID, "");
      •                 if (mTaskpaneHost != null)
      •                 {
      •                     mTaskpaneHost.Init(this.mSWApplication);
      •                 }
      •         }

       

      Please help me out. What am I doing wrong? I think I have to make everything null when I close the add in or so...

        • Re: C# Solidworks crash: Control 'button1' accessed from a thread other than the thread it was created on.
          Artem Taturevych

          Are you clicking the 'button1' on your Task Pane and this exception thrown? Or this is when you create a task pane? This error always indicates that you are trying to call the UI members from another thread. To fix this issue you should call the Invoke method of the control and pass the delegate of the function to process.

           

          Check this MSDN article and sample:

           

          http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx

          __________________________

          Regards,

          Artem Taturevych

          Application Engineer at Intercad

          http://intercad.com.au/

          Tel: +61 2 9454 4444

            • Re: C# Solidworks crash: Control 'button1' accessed from a thread other than the thread it was created on.
              Robin Staes

              This is when I create a task pane. It works fine to switch on and off the add in and so the taskpane. Only when I open a document and then switch on the add in it crashes. When it already is active the add in works fine.

               

              Here the whole class:

               

              1. using System;
              2. using System.IO;
              3. using System.Runtime.InteropServices;
              4. using System.Collections;
              5. using System.Reflection;
              6. using SolidWorks.Interop.sldworks;
              7. using SolidWorks.Interop.swpublished;
              8. using SolidWorks.Interop.swconst;
              9. using SolidWorksTools;
              10. using SolidWorksTools.File;
              11. using System.Collections.Generic;
              12. using System.Diagnostics;
              13. using System.Windows.Forms;
              14. namespace Callback_Test
              15. {
              16.     /// Summary description for Callback_Test.
              17.     [Guid("fb500eff-b1df-40fb-bf7d-09cd2fc48309"), ComVisible(true)]
              18.     [SwAddin(
              19.         Description = "Koppeling Solidworks <-> Isah",
              20.         Title = "Conrad ERP koppeling",
              21.         LoadAtStartup = true
              22.         )]
              23.     public class SwAddin : ISwAddin
              24.     {
              25.         #region Local Variables
              26.         public ISldWorks iSwApp = null;
              27.         ICommandManager iCmdMgr = null;
              28.         public int addinID = 0;
              29.         public int mSWCookie;
              30.         public TaskpaneView mTaskpaneView = null;
              31.         public KoppelingTaskpane mTaskpaneHost = null;
              32.         public SldWorks mSWApplication = null;
              33.         public int mCookie;
              34.         public CommandManager mCommandManager = null;
              35.         public const int mainCmdGroupID = 5;
              36.         public const int mainItemID1 = 0;
              37.         public const int mainItemID2 = 1;
              38.         public const int mainItemID3 = 2;
              39.         public const int flyoutGroupID = 91;
              40.         #region Event Handler Variables
              41.         Hashtable openDocs = new Hashtable();
              42.         SolidWorks.Interop.sldworks.SldWorks SwEventPtr = null;
              43.         #endregion
              44.        
              45.         // Public Properties
              46.         public ISldWorks SwApp
              47.         {
              48.             get { return iSwApp; }
              49.         }
              50.         public ICommandManager CmdMgr
              51.         {
              52.             get { return iCmdMgr; }
              53.         }
              54.         public Hashtable OpenDocs
              55.         {
              56.             get { return openDocs; }
              57.         }
              58.         #endregion
              59.         #region SolidWorks Registration
              60.         [ComRegisterFunctionAttribute]
              61.         public static void RegisterFunction(Type t)
              62.         {
              63.             #region Get Custom Attribute: SwAddinAttribute
              64.             SwAddinAttribute SWattr = null;
              65.             Type type = typeof(SwAddin);
              66.             foreach (System.Attribute attr in type.GetCustomAttributes(false))
              67.             {
              68.                 if (attr is SwAddinAttribute)
              69.                 {
              70.                     SWattr = attr as SwAddinAttribute;
              71.                     break;
              72.                 }
              73.             }
              74.             #endregion
              75.             try
              76.             {
              77.                 Microsoft.Win32.RegistryKey hklm = Microsoft.Win32.Registry.LocalMachine;
              78.                 Microsoft.Win32.RegistryKey hkcu = Microsoft.Win32.Registry.CurrentUser;
              79.                 string keyname = "SOFTWARE\\SolidWorks\\Addins\\{" + t.GUID.ToString() + "}";
              80.                 Microsoft.Win32.RegistryKey addinkey = hklm.CreateSubKey(keyname);
              81.                 addinkey.SetValue(null, 0);
              82.                 addinkey.SetValue("Description", SWattr.Description);
              83.                 addinkey.SetValue("Title", SWattr.Title);
              84.                 keyname = "Software\\SolidWorks\\AddInsStartup\\{" + t.GUID.ToString() + "}";
              85.                 addinkey = hkcu.CreateSubKey(keyname);
              86.                 addinkey.SetValue(null, Convert.ToInt32(SWattr.LoadAtStartup), Microsoft.Win32.RegistryValueKind.DWord);
              87.             }
              88.             catch (System.NullReferenceException nl)
              89.             {
              90.                 Console.WriteLine("There was a problem registering this dll: SWattr is null. \n\"" + nl.Message + "\"");
              91.                 System.Windows.Forms.MessageBox.Show("There was a problem registering this dll: SWattr is null.\n\"" + nl.Message + "\"");
              92.             }
              93.             catch (System.Exception e)
              94.             {
              95.                 Console.WriteLine(e.Message);
              96.                 System.Windows.Forms.MessageBox.Show("There was a problem registering the function: \n\"" + e.Message + "\"");
              97.             }
              98.         }
              99.         [ComUnregisterFunctionAttribute]
              100.         public static void UnregisterFunction(Type t)
              101.         {
              102.             try
              103.             {
              104.                 Microsoft.Win32.RegistryKey hklm = Microsoft.Win32.Registry.LocalMachine;
              105.                 Microsoft.Win32.RegistryKey hkcu = Microsoft.Win32.Registry.CurrentUser;
              106.                 string keyname = "SOFTWARE\\SolidWorks\\Addins\\{" + t.GUID.ToString() + "}";
              107.                 hklm.DeleteSubKey(keyname);
              108.                 keyname = "Software\\SolidWorks\\AddInsStartup\\{" + t.GUID.ToString() + "}";
              109.                 hkcu.DeleteSubKey(keyname);
              110.             }
              111.             catch (System.NullReferenceException nl)
              112.             {
              113.                 Console.WriteLine("There was a problem unregistering this dll: " + nl.Message);
              114.                 System.Windows.Forms.MessageBox.Show("There was a problem unregistering this dll: \n\"" + nl.Message + "\"");
              115.             }
              116.             catch (System.Exception e)
              117.             {
              118.                 Console.WriteLine("There was a problem unregistering this dll: " + e.Message);
              119.                 System.Windows.Forms.MessageBox.Show("There was a problem unregistering this dll: \n\"" + e.Message + "\"");
              120.             }
              121.         }
              122.         #endregion
              123.         #region ISwAddin Implementation
              124.         public SwAddin()
              125.         {
              126.         }
              127.         public bool ConnectToSW(object ThisSW, int cookie)
              128.         {
              129.             mSWApplication = (SldWorks)ThisSW;
              130.             mSWCookie = cookie;
              131.             // Set-up add-in call back info
              132.             bool result = mSWApplication.SetAddinCallbackInfo(0, this, cookie);
              133.           
              134.            
              135.             iSwApp = (ISldWorks)ThisSW;
              136.             addinID = cookie;
              137.             //Setup callbacks
              138.             iSwApp.SetAddinCallbackInfo(0, this, addinID);
              139.            
              140.             #region Setup the Event Handlers
              141.             SwEventPtr = (SolidWorks.Interop.sldworks.SldWorks)iSwApp;
              142.            
              143.             openDocs = new Hashtable();
              144.             AttachEventHandlers();
              145.             #endregion
              146.             this.UISetup();
              147.             return true;
              148.         }
              149.         public bool DisconnectFromSW()
              150.         {
              151.             DetachEventHandlers();
              152.             System.Runtime.InteropServices.Marshal.ReleaseComObject(iSwApp);
              153.             iSwApp = null;
              154.            
              155.             //The addin _must_ call GC.Collect() here in order to retrieve all managed code pointers
              156.             GC.Collect();
              157.             GC.WaitForPendingFinalizers();
              158.             GC.Collect();
              159.             GC.WaitForPendingFinalizers();
              160.             this.UITeardown();
              161.             return true;
              162.         }
              163.         #endregion
              164.         #region UI Methods
              165.         public void UISetup()
              166.         {
              167.             mTaskpaneView = mSWApplication.CreateTaskpaneView2(Assembly.GetExecutingAssembly().Location.Replace(".dll", ".bmp"), "Solidworks <-> Isah Koppeling");
              168.             mTaskpaneHost = (KoppelingTaskpane)mTaskpaneView.AddControl(KoppelingTaskpane.SWTASKPANE_PROGID, "");
              169.             if (mTaskpaneHost != null)
              170.             {
              171.                 mTaskpaneHost.Init(this.mSWApplication);
              172.             }
              173.         }
              174.         public void UITeardown()
              175.         {
              176.             mTaskpaneHost = null;
              177.             mTaskpaneView.DeleteView();
              178.             Marshal.ReleaseComObject(mTaskpaneView);
              179.             mTaskpaneView = null;
              180.             //iSwApp = null;
              181.             //iCmdMgr = null;
              182.             //addinID = 0;
              183.             //mTaskpaneView = null;
              184.             //mTaskpaneHost = null;
              185.             //mSWApplication = null;
              186.             //mCommandManager = null;
              187.             //try
              188.             //{
              189.             //    foreach (Process proc in Process.GetProcessesByName("SLDWorks"))
              190.             //    {
              191.             //        proc.Kill();
              192.             //    }
              193.             //}
              194.             //catch (Exception ex)
              195.             //{
              196.             //    MessageBox.Show(ex.Message);
              197.             //}
              198.             //mSWApplication.ExitApp();
              199.             //iSwApp.ExitApp();
              200.             this.mSWApplication = null;
              201.             KoppelingTaskpane.threadstop = true;
              202.         }
              203.         public bool CompareIDs(int[] storedIDs, int[] addinIDs)
              204.         {
              205.             List<int> storedList = new List<int>(storedIDs);
              206.             List<int> addinList = new List<int>(addinIDs);
              207.             addinList.Sort();
              208.             storedList.Sort();
              209.             if (addinList.Count != storedList.Count)
              210.             {
              211.                 return false;
              212.             }
              213.             else
              214.             {
              215.                 for (int i = 0; i < addinList.Count; i++)
              216.                 {
              217.                     if (addinList[i] != storedList[i])
              218.                     {
              219.                         return false;
              220.                     }
              221.                 }
              222.             }
              223.             return true;
              224.         }