Unable to invoke target method in current thread. Use `BeginInvokeOnMainThread` method to prevent this error
Unable to invoke target method in current thread. Use `BeginInvokeOnMainThread` method to prevent this error
19 Jul 2022, 13:19
When I try to execute any cAlgo method from another thread I get this error:
Unable to invoke target method in current thread. Use `BeginInvokeOnMainThread` method to prevent this error.
at cTrader.Automate.Host.Runtime.Instances.SmallAlgoInstanceBase`1.HandleDispatcherUnexpectedThread()
at cTrader.Automate.Host.AutomateTargetSessionController.OnDispatcherUnexpectedThread()
at cTrader.Automate.Adapters.SymbolApi.SymbolsProviderAdapter.GetSymbols()
at cAlgo.API.Internals.Algo.get_Symbols()
After a while I realized that cAlgo offers this "BeginInvokeOnMainThread" method. Although that only executes some code asynchronously in the main thread there is no way to return a value from it.
After a while again I noticed how messed up is this thread model in cTrader 4.3.
Basically every call seems to be checked if it is being executed in the main thread.
I had created a bot that, for instance, on position open, it would do a GRPC call to another application which in turn could call ctrader to execute something like create a new pending order.
The issue now is that GRPC will execute in another thread in cTrader when receiving a call from another application. That other thread will need to access the main thread, which in turn is locked because of the GRPC outgoing call on position open. As a result I have a deadlock.
Any ideas on how to workaround that?
I don't get why it has been made this so strict way that everything must go through the main thread.
0000wj
24 Jul 2022, 07:11
+1 on this.
Basically this is backward incompatible. My old code broke
@0000wj