none
System.Reflection.TargetInvocationException ocurred in mscorlib.dll

    Question

  • Hi,

    I have developed a small C# application that will just monitor write changes in a "file.txt" and send signals accordingly to a bank of relays. The text file is updated by a test program. I am basically using this "file.txt" as a comms buffer between this two applications.

    Both this applications run side by side and when the test program finishes its sequence it simple restarts creating again the file.txt.

    Everything works fine but quite often when the test application restarts the execution of the test I get this error:

    "An unhandled exception of type 'System.Reflection.TargetInvocationException' ocurred in mscorlib.dll - Additional information: Exception has been thrown by the target of an invocation"

    When this happens, the C# aplication breaks point to main() at the Application.Run(new Form1()). 

    I see this error with less frequency if after every cycle I close down both the C# and the test application but even then.

    I hope you guys can please help me, I do not understand why this error happens since the only thing my C# application is suppose to react to is to write changes to file.txt.

    Best Regards

    Manuel

    Thursday, April 22, 2010 11:12 AM

Answers

  • Form1 receives a file changed event and is attempting to read or write to a file of which is already opened.  The file name is KeyTest.txt and is found in the Documents and Settings folder for the administrator.  I would examine all my code for who access this file.  Then I'd consider (being that it's an administrator account) if there are multiple instances of my program attempting to access file at same time.  If true, I'd write a back-off algorhythm which would wait  and retry in an exponential timed wait pattern.  Finally if after the retries time-out, I would issue an error to the appropriate location.


    Javaman
    Wednesday, May 05, 2010 1:04 PM

All replies

  • How is the test application getting "restarted"?
    If you're just looking to have the application repeat a process again it's best to use a loop, or create a service to run in the background and continuously perform some operations.

    Also, how are you monitoring the changes to the file using the second application?

    Thursday, April 22, 2010 5:04 PM
  • Hi,

    Thanks for your replay.

    At this stage the test application is restarted manually, more than restarted I would say it re-excutes a test script, since the test application does not close down. The plan is that the test application will run through a number of different test scripts automatically.

    The test application is an old program being used in my company to test keyboards a there are not plans to replace it. I have been assigned with the task of automating the key entry proccess during tests. To achieve this I am modifying the test scripts so they will write the key need it to be pressed into a text file and here is where my application comes into play.

    My C# application will read the string saved into the text file, decode it, start a timer to give the test application time to get into the key waiting mode and when timer ends send the value to a bank of solenoids for key pressing; the test application registers the key press and the procces is repeated all over again. My application monitors the changes in the text file with a file system watcher catching the LastWrite's file change event. Here is the code for the event handler if it is of any help:

        private void fileSystemWatcher1_Changed(object sender, System.IO.FileSystemEventArgs e)
        {
          string path = @"C:\Documents and Settings\Administrator\Desktop\KeyTest.txt";
    
          FileStream KeyTestFileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
          StreamReader KeyTestStreamReader = new StreamReader(KeyTestFileStream);
    
          string str = KeyTestStreamReader.ReadLine();
    
          KeyTestStreamReader.Close();
          KeyTestFileStream.Close();
    
          if (str == null)
            return;
    
          //Resets any previously pressed key.
          if (KeyPressed)
          {
            BitValue = MccDaq.DigitalLogicState.Low;
            MccDaq.ErrorInfo ULStat = DaqBoard.DBitOut(PortType, BitIndex, BitValue);
            KeyPressed = false;
          }
    
          if (str.Contains("TESTPRESS"))
          {
            TestPress_label.Text = str[11].ToString();
            TestPress = Encoding.ASCII.GetBytes(str[11].ToString());
            Cooling_timer.Start();
          }
          else if(str.Contains("TEST ENDED"))
          {
            TestPress_label.Text = "#";
            Reset_USB_ERB24();
          }
          else
            return;
        }
    

    Thanks again for your help.

    Friday, April 23, 2010 9:32 AM
  • Hi,

    There can be multiple causes of this exception. I would suggest to look into following scenaiors and evaluate your case.

    1- Your application is communicationg with remote system which may go offline sometime during data upload from your application

    2- Your application is referencing some external dll and there is a naming conflict.

    Also please note that 'InnerException' property inside Exception class always gives you some more concrete clue about the problem. Please post inner exception here and I will see if I could suggest you some solution.

    Naeem

    Friday, April 23, 2010 11:15 AM
  • Post the stack trace
    Javaman
    Friday, April 23, 2010 11:17 AM
  •  	mscorlib.dll!System.Delegate.DynamicInvokeImpl(object[] args) + 0x5a bytes	
     	System.Windows.Forms.dll!System.Windows.Forms.Control.InvokeMarshaledCallbackDo(System.Windows.Forms.Control.ThreadMethodEntry tme) + 0x9d bytes	
     	System.Windows.Forms.dll!System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(object obj) + 0x6b bytes	
     	mscorlib.dll!System.Threading.ExecutionContext.runTryCode(object userData) + 0x43 bytes	
     	[Native to Managed Transition]	
     	[Managed to Native Transition]	
     	mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0xa7 bytes	
     	mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x92 bytes	
     	System.Windows.Forms.dll!System.Windows.Forms.Control.InvokeMarshaledCallback(System.Windows.Forms.Control.ThreadMethodEntry tme) + 0x90 bytes	
     	System.Windows.Forms.dll!System.Windows.Forms.Control.InvokeMarshaledCallbacks() + 0xb3 bytes	
     	System.Windows.Forms.dll!System.Windows.Forms.Control.WndProc(ref System.Windows.Forms.Message m) + 0x800 bytes	
     	System.Windows.Forms.dll!System.Windows.Forms.ScrollableControl.WndProc(ref System.Windows.Forms.Message m) + 0x45 bytes	
     	System.Windows.Forms.dll!System.Windows.Forms.ContainerControl.WndProc(ref System.Windows.Forms.Message m) + 0x13 bytes	
     	System.Windows.Forms.dll!System.Windows.Forms.Form.WndProc(ref System.Windows.Forms.Message m) + 0x2b6 bytes	
     	System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.OnMessage(ref System.Windows.Forms.Message m) + 0xd bytes	
     	System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.WndProc(ref System.Windows.Forms.Message m) + 0xd6 bytes	
     	System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.DebuggableCallback(System.IntPtr hWnd, int msg = 49627, System.IntPtr wparam, System.IntPtr lparam) + 0x75 bytes	
     	[Native to Managed Transition]	
     	[Managed to Native Transition]	
     	System.Windows.Forms.dll!System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(int dwComponentID, int reason = -1, int pvLoopData = 0) + 0x2ea bytes	
     	System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(int reason = -1, System.Windows.Forms.ApplicationContext context = {System.Windows.Forms.ApplicationContext}) + 0x17d bytes	
     	System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoop(int reason, System.Windows.Forms.ApplicationContext context) + 0x53 bytes	
     	System.Windows.Forms.dll!System.Windows.Forms.Application.Run(System.Windows.Forms.Form mainForm) + 0x2e bytes	
    >	KeyTestMonitor.exe!KeyTestMonitor.Program.Main() Line 18	C#
     	[Native to Managed Transition]	
     	[Managed to Native Transition]	
     	mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args) + 0x32 bytes	
     	Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() + 0x2b bytes	
     	mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) + 0x3b bytes	
     	mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x81 bytes	
     	mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x40 bytes	
    
    Friday, April 23, 2010 12:56 PM
  • Hi Naeem

    How do I access the inner exception? Sorry for my lack of knowledge but I am new.

    Thanks

    Manuel

    Friday, April 23, 2010 12:58 PM
  • Ok post the code to System.Windows.Forms.Application.Run.
    Javaman
    Friday, April 23, 2010 1:10 PM
  • Hi Javaman,

    using System;
    using System.Collections.Generic;
    using System.Windows.Forms;
    
    namespace KeyTestMonitor
    {
      static class Program
      {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
          Application.EnableVisualStyles();
          Application.SetCompatibleTextRenderingDefault(false);
          Application.Run(new Form1());
        }
      }
    }

    Is this what need?

    Thanks

    Manuel

    Friday, April 23, 2010 1:42 PM
  • Sorry, I thought it was some other run method, step into your code and show the method that you are in when the exception happens.  Then pinpoint the exact Line Of Code that causes isse.
    Javaman
    Friday, April 23, 2010 3:52 PM
  • Hi Manuel,

     

    How is the problem now?   Any update? 

     

     

    Have a nice day!

     

     

    Best Regards,
    Lingzhi Sun

    MSDN Subscriber Support in Forum

    If you have any feedback on our support, please contact msdnmg@microsoft.com


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Thursday, April 29, 2010 9:27 AM
  • Hi Javaman,

    I can not step into my code because the exception occurs and breaks at Application.Run(new Form1()); if I try to step into, the applications exits completely.

    Apparently the exception is thrown because my application tries to access the file and can not at creation time. You see this is what i do not understand, why my application trys to get access to the file at creation time when it is set to recceive just write events into that text file.

    Any ideas? Thanks

    Manuel

    Thursday, April 29, 2010 11:24 AM
  • Hi,

    The problem is not resolved yet.

    Thanks for your interest.

    Best Regards,

    Manuel

    Thursday, April 29, 2010 11:26 AM
  • When the application breaks, click on 'Details'. It will open a window where you should see the exception being thrown. At the left, click on the + to expand it and look at the InnerException line.
    Thursday, April 29, 2010 12:54 PM
  • Hi Manuel,

     

    Have you followed Louis's suggestion to check the InnerException message?  

     

     

    Have a nice day!

     

     

    Best Regards,
    Lingzhi Sun

    MSDN Subscriber Support in Forum

    If you have any feedback on our support, please contact msdnmg@microsoft.com


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Wednesday, May 05, 2010 1:46 AM
  • Hi Louis,

    Thanks for your replay and sorry for my delay replaying but given the random nature of the fault it has taken a while this time around for the fault to occur. Here it is, I have been using the release version of my application this time and the details of the exception thrown are shown below but I could not find any InnerException details: 

    See the end of this message for details on invoking 
    just-in-time (JIT) debugging instead of this dialog box.
    
    ************** Exception Text **************
    System.IO.IOException: The process cannot access the file 'C:\Documents and Settings\Administrator\Desktop\KeyTest.txt' because it is being used by another process.
      at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
      at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
      at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
      at KeyTestMonitor.Form1.fileSystemWatcher1_Changed(Object sender, FileSystemEventArgs e)
    
    
    ************** Loaded Assemblies **************
    mscorlib
      Assembly Version: 2.0.0.0
      Win32 Version: 2.0.50727.42 (RTM.050727-4200)
      CodeBase: file:///C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/mscorlib.dll
    ----------------------------------------
    KeyTestMonitor
      Assembly Version: 1.0.0.0
      Win32 Version: 1.0.0.0
      CodeBase: file:///C:/Documents%20and%20Settings/Administrator/Desktop/KeyTestMonitor.exe
    ----------------------------------------
    System.Windows.Forms
      Assembly Version: 2.0.0.0
      Win32 Version: 2.0.50727.42 (RTM.050727-4200)
      CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Windows.Forms/2.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
    ----------------------------------------
    System
      Assembly Version: 2.0.0.0
      Win32 Version: 2.0.50727.42 (RTM.050727-4200)
      CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System/2.0.0.0__b77a5c561934e089/System.dll
    ----------------------------------------
    System.Drawing
      Assembly Version: 2.0.0.0
      Win32 Version: 2.0.50727.42 (RTM.050727-4200)
      CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Drawing/2.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
    ----------------------------------------
    MccDaq
      Assembly Version: 1.3.13.0
      Win32 Version: 1.3.13.0
      CodeBase: file:///C:/WINDOWS/assembly/GAC/MccDaq/1.3.13.0__a37eefcf5c6ca10a/MccDaq.dll
    ----------------------------------------
    
    ************** JIT Debugging **************
    To enable just-in-time (JIT) debugging, the .config file for this
    application or computer (machine.config) must have the
    jitDebugging value set in the system.windows.forms section.
    The application must also be compiled with debugging
    enabled.
    
    For example:
    
    <configuration>
      <system.windows.forms jitDebugging="true" />
    </configuration>
    
    When JIT debugging is enabled, any unhandled exception
    will be sent to the JIT debugger registered on the computer
    rather than be handled by this dialog box.
    
    
    

    When using the debug version of my application I could not get any of the details that you mention in your post, the only information I get is the message posted above in my previous posts, I might not be looking in the right place though I am relatively new.

    Coming back to this post, I understand from this that my application "KeyTestMonitor.exe" can not acces "KeyTest.txt" because it is being use by another application. Am I right?

    This error happens right after start execution of the test. At this point the test application creates "KeyTest.txt", what I do not understand is why my application tries to acces the file at creation when its fileSystemWatcher is set to receive just the write events.

    I am going to try activating the JIT debugger now and see if it gives any more information.

    Thanks very much.

    Manuel

    Wednesday, May 05, 2010 8:34 AM
  • Hi Lingzhi,

    Sorry for the delay replaying but the nature of this bug it is quite random and it has taken a while this time to replicate.

    Best Regards

    Manuel

    Wednesday, May 05, 2010 8:36 AM
  • Form1 receives a file changed event and is attempting to read or write to a file of which is already opened.  The file name is KeyTest.txt and is found in the Documents and Settings folder for the administrator.  I would examine all my code for who access this file.  Then I'd consider (being that it's an administrator account) if there are multiple instances of my program attempting to access file at same time.  If true, I'd write a back-off algorhythm which would wait  and retry in an exponential timed wait pattern.  Finally if after the retries time-out, I would issue an error to the appropriate location.


    Javaman
    Wednesday, May 05, 2010 1:04 PM
  • Hi everybody,

    The problem was down to the way windows was sharing proccesing time between my keytestmonitor application and the test application updating the test file my application monitored.

    It is probably not the most elegant solution but I solved the problem introducing a do/while loop in my application before trying to acces the KeyTest.txt. This loop will basically sit and wait until the txt file has been freed:

          do
            Thread.Sleep(5);
          while (CheckIfFileIsBeingUsed(path));
    
    
    public bool CheckIfFileIsBeingUsed(string fileName)
        {
          try
          {
            File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
          }
    
          catch (IOException)
          {
            return true;
          }
          return false;
        }
    
    

    Again thanking everybody who tried to help replaying to this thread.

    Manuel

    Thursday, August 26, 2010 3:56 PM