beckhoff TE1000 TwinCAT 3 — 6.3.6 Avoiding COM exceptions caused by incorrect Thread Apartments

Samples | System because the COM server cannot directly handle the call from the foreign apartment. This is not a defect in the Automation Interface, but rather a fundamental property of STA-COM objects. The solution is to consistently provide a dedicated STA thread. The problem // WRONG — BackgroundWorker uses thread-pool threads (MTA) var worker = new BackgroundWorker(); worker.DoWork += (sender, e) => { // RPC_E_SERVERCALL_RETRYLATER: COM object is STA, thread is MTA sysManager.LookupTreeItem("TIPC^PLC1"); // Error! }; worker.RunWorkerAsync(); The same applies to Task.Run(() => ...) and ThreadPool.QueueUserWorkItem(...) , since they all use MTA pools. Solution:

Explicitly creating an STA thread public static class AsyncFactory { private static StaTaskScheduler _sta = new StaTaskScheduler(numberOfThreads:

1); public static async Task StartNew(Action action, bool configureAwait = false) { try { await Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, _s ta).ConfigureAwait(configureAwait); } catch (Exception ex) { throw ex; } } public static async Task StartNew (Func function, bool configureAwait = false) { try { return await Task.Factory.StartNew(function, CancellationToken.None, TaskCreationOptions .None, _sta).ConfigureAwait(configureAwait); } catch (Exception ex) { throw ex; } } } This AsyncFactory can now be used to start tasks that run concurrently and do not block the main thread.

It is crucial that all COM objects be created and used within the actions queued via the factory. This ensures that they run on the scheduler's STA thread and are addressed from there. The following example shows a typical application flow in which tasks are passed to the AsyncFactory one after another: create a DTE instance, create a solution with a TwinCAT project, query the ITcSysManager , execute a longer-running COM operation, and finally clean up. await RunTwinCATAsync(); async Task RunTwinCATAsync() { Console.WriteLine($"Main thread: {Environment.CurrentManagedThreadId}"); // Step 1 - Create a new DTE instance on the STA thread.

// The MessageFilter is registered to handle RPC_E_CALL_REJECTED errors. DTE dte = await AsyncFactory.StartNew(() => { MessageFilter.Register(); Console.WriteLine($"STA thread: {Environment.CurrentManagedThreadId}"); Type t = Type.GetTypeFromProgID("TcXaeShell.DTE.17.0"); DTE instance = (DTE)Activator.CreateInstance(t); TE1000 207 Version: 1.7.0