I’ve run into OnBarUpdate or OnMarketData reading/writing along with OnRender and I wonder if there are recommended NT ways to handle it?
For my particular issue where OnBarUpdate was writing on bar close I implemented a lock there and made OnRender return when lock exists:
if (!System.Threading.Monitor.TryEnter(pivotLock)) { return; }
The reason I’m asking is because AI is either recommending double or triple buffering, or locks sprinkled everywhere, but I think ‘my way’ ™ above is better for performance which made me wonder if there are other ways?
The race is real by design: the NinjaScript Best Practices page says OnRender runs on the UI thread, while market data events run on the instrument thread pool. So OnBarUpdate/OnMarketData and OnRender can overlap.
Your TryEnter-and-skip is a sound choice, since it never blocks the UI thread. The catch is that OnRender only runs when the chart repaints, so a skipped frame can sit stale until the next mouse move or tick. Calling ForceRefresh() right after you release the lock in OnBarUpdate covers that.
If you want no lock at all: build the new data into a fresh object (a new list or array) in OnBarUpdate, then publish it by swapping one field reference (Volatile.Write or Interlocked.Exchange). OnRender reads that field once into a local and draws from the local. The writer never mutates anything the renderer can see, so there’s nothing to lock and no skipped frames. That’s really all “double buffering” needs to mean here.
One related trap: the same page notes barsAgo-indexed values aren’t guaranteed to be in sync inside OnRender, since it isn’t a market data event. Use absolute indexes there (ChartBars.FromIndex to ToIndex with GetValueAt) rather than Close[0]-style access.
1 Like