Soy nuevo en COM y trato de entender la diferencia entre STA y MTA. Traté de crear un ejemplo que muestre que COM puede administrar llamadas al objeto creado en STA que no es seguro para subprocesos.No se puede llamar al objeto COM creado a partir de STAThread desde sus hilos STA
MyCalcServer
clase aquí se crea utilizando ATL Simple Object. Los ajustes utilizados son los mismos que en this article:
- modelo de subprocesos: Apartamento
- Agregación: Sin
- Interfaz: personalizada
MyCalcServer
objeto COM se utiliza en otro proyecto de C# que es:
class Program
{
[STAThread]
static void Main(string[] args)
{
MyCOMLib.MyCalcServer instance = new MyCOMLib.MyCalcServer();
string output1;
instance.ChangeValue("Gant", out output1);
Console.WriteLine(output1);
Thread t1 = new Thread(() =>
{
while (true)
{
string output;
instance.ChangeValue("Gant", out output);
Console.WriteLine(output);
}
});
t1.SetApartmentState(ApartmentState.STA);
t1.Start();
// :
// also has t2 and t3 here with similar code
// :
t1.Join(); t2.Join(); t3.Join();
}
}
Sin embargo, esto siempre da como resultado InvalidCastException
(E_NOINTERFACE) levantado dentro del código de t1. También intenté cambiar ApartmentState por MTA sin éxito.
Unable to cast COM object of type 'MyCOMLib.MyCalcServerClass' to interface type 'MyCOMLib.IMyCalcServer'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{B005DB8C-7B21-4898-9DEC-CBEBE175BB21}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
¿Alguien podría explicar lo que estoy haciendo mal aquí?
Tal vez el JIT cree que no está utilizando "instancia" y lo lanza temprano. intenta poner Marshal.ReleaseComObject (instancia) después de las uniones. – adrianm
@adrianm Todavía no funciona pero gracias por esto – Gant
Intente cambiar la primera línea a MyCOMLib.IMyCalcServer instancia = new MyCOMLib.MyCalcServer(); Creo que solo las interfaces (no las clases) se pueden ordenar entre subprocesos. – adrianm