0
Answer

Strange Invocation Error on my Form

Will

Will

16y
4.6k
1

Hey guys, I'm writing a fairly large project (by my standards), and have two processes that are interacting. My .dll which is interfacing with hardware is raising events, which are caught by my main program, running on a windows form.

I'm using the following piece of code to invoke the event on the form thread, so I can display the results:

void ComLib_DataReceived(object sender, DataReceivedEventArgs e)

{

   postDataReceived(e);

}

delegate void postDataReceivedCallback(DataReceivedEventArgs e);

private void postDataReceived(DataReceivedEventArgs e)

{

   if (this.tbConsoleMessages.InvokeRequired)

   {

      postDataReceivedCallback d = new postDataReceivedCallback(postDataReceived);

      this.Invoke(d, new object[] { e });

   }

   else

   {

      //Do something on the form

   }

Now, 95% of the time, this code works fine. However, once in a while, I get the error:

System.ArgumentOutOfRangeException was unhandled
  Message="Index and length must refer to a location within the string.\r\nParameter name: length"
  Source="System.Windows.Forms"
  ParamName="length"
  StackTrace:
       at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
       at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
       at myProgram.Form1.postDataReceived(DataReceivedEventArgs e)
       at myProgram.Form1.ComLib_DataReceived(Object sender, DataReceivedEventArgs e)
       at myLibrary.ComLib.DataReceivedEventHandler.Invoke(Object sender, DataReceivedEventArgs e)
       at myLibrary.ComLib.serialPort1_OnDataReceived(Object sender, SerialDataReceivedEventArgs e) in C:\Users\****\Documents\Visual Studio 2008\Projects\myLibrary\myLibrary\Class1.cs:line 223
       at System.IO.Ports.SerialPort.CatchReceivedEvents(Object src, SerialDataReceivedEventArgs e)
       at System.IO.Ports.SerialStream.EventLoopRunner.CallReceiveEvents(Object state)
       at System.Threading._ThreadPoolWaitCallback.WaitCallback_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(_ThreadPoolWaitCallback tpWaitCallBack)
       at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(Object state)
  InnerException:

Note that my DataReceivedEventArgs is just two ints and a string. And I know the string is not being accessed out of range. It isn't my code (I strongly believe) but rather something else. It's so wierd that it runs for a while, than crashes, or sometimes crashes the very first time. I've no idea...

Can anyone give me a possible cause and/or solution? It would be greatly appreciated;