Here is my code, a simplified version
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using RDSCOMMUNICATORLib;
using System.Timers;
using System.Threading;
namespace RDSConsoleApplication
{
class Program
{
static public RDSComClass oObj = new RDSComClass();
static void Main(string[] args)
{
try
{
oObj.Host = "127.0.0.1";
oObj.Port = 2902;
oObj.LoadPiece(); // OK HERE
IConnectionEvents_OnPieceEventHandler PieceArraved = new IConnectionEvents_OnPieceEventHandler(oObj_OnPiece);
oObj.OnPiece += PieceArraved;
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
} // end main
static public void oObj_OnPiece(int lLSCRef, string strLSCName, int lPieceNumber, int bWithScans)
{
try
{
// HERE WE START GETTING EXCEPTION "Unable to cast COM object of type.....
// The application called an interface that was marshalled for a different thread"
oObj.LoadPiece();
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
} // end class Program
} // end namespace
I am referencing a COM object inside C# console application that serves as a gateway to connect to the back end and periodically receive some "piece" objects.
As a test, when I try from within the main method all works fine: I can connect, receive "piece" object and access its properties. The problem is that I need to receive and process that same "piece" object from within oObj_OnPiece callback method, and it throws the above mentioned exception. I browsed other similar posts, I understand it's a threading issue, but not sure how to resolve it. Any help is appreciated.