WPF Thread: "A COM object that has been separated from its base RCW cannot be used."

I get the following error:

"COM object that has been separated from its underlying RCW cannot be used."

I am sure that the problem is that the COM object is not called in the thread that was created - STA. I tried to implement IDisposable, but it did not work for me.

There are several posts devoted to a similar problem, but which still do not solve my problem:

Is it safe to call RCW from the finalizer? Release the Excel object in my destructor

Can someone post an example / explain how a COM object should be correctly accessible from another thread?

Here is the minimal code that shows the problem:

using System;
using System.Threading;

namespace Test.ComInterop
{
    public class Program
    {
        MyCom _myCom;

        [STAThread]
        static void Main( string[] args )
        {
            new Program();
        }

        public Program()
        {
            _myCom = new MyCom();

            // this method call works
            string version = _myCom.ComMethod();

            StartThread();
        }

        private void StartThread()
        {
            Thread t = new Thread( UIRun );
            t.SetApartmentState( ApartmentState.STA );
            t.Start();
        }

        void UIRun()
        {
            TestUI window = new TestUI();
            window.Show();

            // this method call fails
            window.Title = _myCom.ComMethod();

            window.Closed += ( sender2, e2 ) 
                => window.Dispatcher.InvokeShutdown();

            System.Windows.Threading.Dispatcher.Run();
        }
    }

    class MyCom
    {
        private dynamic _com;
        public MyCom()
        {
            _com = Activator.CreateInstance(
                Type.GetTypeFromProgID( "Excel.Application" ) );
        }

        public string ComMethod()
        {
            return (string) _com.Version;
        }
    }    
}
0
4

, . COM-, , . .NET CoUninitialize() COM-. - .

. , , .

+4

, COM- - , Marshal. . COM- , - , .

, , , .

MTA?

+2

, , . -. , .

COM- Excel - COM, , , Excel COM.

COM- Excel ( MsProject). Excel Excel . Excel API . , , . .

, , , en/US ( LCID). :

.

+1

MyCom DispatcherObject. , , _myCom.Dispatcher.Run(). COM-, _myCom.Dispatcher.BeginInvoke/Invoke.

+1

All Articles