Retry after delay without blocking possible (similar to setTimeout() in JS)?

Created at 12 Feb 2025, 09:50
How’s your experience with the cTrader Platform?
Your feedback is crucial to cTrader's development. Please take a few seconds to share your opinion and help us improve your trading experience. Thanks!
QW

qwer1993

Joined 12.02.2025

Retry after delay without blocking possible (similar to setTimeout() in JS)?
12 Feb 2025, 09:50


Hey,

is there a way to retry some operations after some time or delay the execution of some operations without blocking.

I need something like setTimeout() from JavaScript.

I tried out the sleep() function but it blocks the execution and if my Websocket message handler calls the sleep function it doesn't receive further messages as long sleep() function is active…


@qwer1993
Replies

firemyst
18 Feb 2025, 01:14

the calgo documentation specifically states:

“The sleep functionality is available only for .NET 6 algos. While a cBot stays in sleep mode, all other events in the code will be ignored.”

 

If you need to do other things, then you obviously need to set your own timer and check if after x-seconds/minutes/hours/whatever.

So create your own timer, and set a flag after the desired amount of time has elapsed. When the flag is set to true, then continue executing whatever code you need to. In the mean time, you should still be able to listen to messages from whatever sockets you have set up.


@firemyst

qwer1993
18 Feb 2025, 07:24 ( Updated at: 28 Feb 2025, 09:09 )

I figured it out myself. If anybody need somehting similar just try this pattern (BeginInvokeOnMainThread very important otherwise your code will be buggy and forget the “await” operator it will not work because thread will be changed after await):

Task.Delay(waitInMs)
                    .ContinueWith((t) => BeginInvokeOnMainThread(() => yourRetryOperation()));

@qwer1993

qwer1993
18 Feb 2025, 07:24 ( Updated at: 28 Feb 2025, 09:09 )

I figured it out myself. If anybody need somehting similar just try this pattern (BeginInvokeOnMainThread very important otherwise your code will be buggy and forget the “await” operator it will not work because thread will be changed after await):

Task.Delay(waitInMs)
                    .ContinueWith((t) => BeginInvokeOnMainThread(() => yourRetryOperation()));

@qwer1993