Files
mika@stocksharp.com 4203be8f5c Unwind the blocking waits left by the async rework and fix what it uncovered
"Mark the blocking wrappers obsolete" left several callers of those wrappers
under #pragma, because a property, a parameter handler or a state setter could
not wait, and a few places that blocked without a wrapper. Each of those
chains now runs through callers that can await.

The emulation connector. A state change collects what its handlers throw and
sends it out once the state lock is released; the disconnect that follows
Stopping is awaited there as well. The change to Stopped moved from a handler
of Disconnected into OnDisconnectedAsync, a step the connector now awaits
before it raises that event.

ExpressionIndexSecurity. Expression records the text and reads the instruments
it names, which needs no compiler. The formula is compiled by GetFormulaAsync;
Formula is an obsolete blocking wrapper over it. IBasketSecurityProcessor gets
InitAsync, where the expression processor takes its formula, and
CreateProcessorAsync creates a processor and prepares it; CreateProcessor and
the IEnumerable ToBasket are obsolete wrappers, and the tests of ToBasket go
through the IAsyncEnumerable overload. The index diagram element builds its
index in OnPrepareAsync.

MathDiagramElement. The inputs are named by the text of the formula; the
formula and its validation are compiled in OnPrepareAsync. An element that was
reset therefore compiles again at the next start instead of refusing to start.
An input that is wired stays while the text is not known to compile, and goes
at the preparation if the compiled formula does not name it. A text replaced
under a running element is an error on every value until the element is
prepared again.

Candle patterns. A CandleExpressionCondition compiled its formula in the
constructor or, for the registry, at the first evaluation. The formula is now
compiled by PrepareAsync: on the condition, on ICandlePattern and, through the
new IIndicator.PrepareAsync, on the indicator that holds a pattern. A pattern
that was not prepared refuses to recognize instead of compiling on the spot.
The checks of a pattern as a whole - a formula reaching outside it, no
formulas at all - moved from the first Recognize to the preparation, and a
failed check no longer leaves the pattern marked as checked. Whoever feeds an
indicator prepares it first: IndicatorDiagramElement in OnPrepareAsync, a
strategy for the indicators its start registered, the chart samples when an
indicator is added. ICandlePatternProvider.Save became SaveAsync and prepares
the pattern before it stores it. The compileOnDemand constructor is gone: no
constructor compiles.

Stopping a strategy from code that cannot wait. When an element was entered
deeper than the overflow limit, DiagramElement.Process stopped the strategy
through AsyncHelper.Run. Strategy gets RequestStop for such code: it reports
the error, refuses new orders at once and leaves the stop itself to
OnNewMessage, which carries it out when the connector hands over the next
message.

Releasing a connector. Connector.DisposeManaged waited for the disconnect, and
for the message that takes the adapters apart, through AsyncHelper.Run. The
release is now DisposeManagedAsync, a virtual chain that the connectors
derived from Connector override. DisposeAsync awaits it, and the sealed
DisposeManaged is the same chain with the caller blocked, as IDisposable
requires. IConnector is IAsyncDisposable, so code that holds a connector by
its interface releases it by await as well.

Diagram elements that waited for their type. A composition read before one of
its element types was registered keeps an empty node for each such element.
Registering the type started their load unawaited, and a failure lost the
settings at the next save. ICompositionRegistry gets
LoadNotLoadedElementsAsync, to be awaited by whoever registered the types. It
loads what waits in the given composition and in the compositions nested in
it, one call at a time. The settings of an element that waits are kept by its
node (ICompositionModelNode.ElementSettings). A loaded element joins its
model: it is announced as an added one and the links of its node are
connected.

The sample windows. CombineHistoryRealtime, LiveTerminal and StoreDataLocal,
WPF and Avalonia, flushed the storage executor, released the CSV registries
and read them at startup through AsyncHelper.Run. A window now refuses the
first attempt to close it, awaits the release and closes itself once the
queued writes are on the disk. A shutdown that does not honour the refusal -
the end of the Windows session, Application.Shutdown - is not waited for: what
is still queued then is lost. LiveOptionsQuoting and MultiConnect called the
blocking Strategy.Start, Stop and GetTimeFrames under a suppressed obsolete
warning; they await the async ones now.

What the rework uncovered:

- Pausing the optimizer. An iteration that had passed the pause gate but
  whose connector had not started replaying yet ran to its end through the
  pause; cloning the strategy asynchronously made that window long enough for
  PauseHaltsBruteForce to see it on CI. An iteration now waits for its
  connector to come up and suspends it if the optimizer is paused by then.
- Undo of diagram elements. An undo scope opened with no undo manager in
  sight took the element's level down when it closed, so the level was
  negative by the time the element reached a composition and no edit was ever
  reported. The scope remembers whether it was counted.
- Undo of a chart panel. A snapshot keeps the series and axes of a panel by
  reference, since a part can only be saved asynchronously, so undo did not
  put back what a part was set to. IChartSnapshotPart is an optional interface
  for a part that can copy its settings in memory; the panel captures and
  gives back the settings of such parts. No chart part implements it yet -
  that is for the chart packages to do.
- The dummy indicator wrapper was left without a chart element, so indicator
  values could not be wired into the panel that a run without a window uses.
- Settings loaded before a composition existed are applied when the strategy
  starts; a test pins it.
- AsyncMessageChannel looked at its state once per wake-up and then went
  through the queue until it was empty, so a message sent right after Suspend
  returned could still be started, and Suspend_PausesProcessing was red from
  time to time. The state is now read under the queue lock, where the next
  message is picked; a channel that is being closed stops starting what is
  queued the same way.

DiagramElementParamTests no longer declares a value that persists itself
through the obsolete IPersistable: declaring one needs a suppressed warning,
and for that contract the parameter relies on SaveEntireAsync and
LoadEntireAsync of Ecng, which are tested there.
2026-10-04 18:59:25 +03:00

117 lines
2.8 KiB
C#

namespace StockSharp.Samples.Advanced.MultiConnect;
using System;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Threading;
using Ecng.Common;
using Ecng.Configuration;
using Ecng.ComponentModel;
using Ecng.Logging;
using Ecng.IO;
using StockSharp.Configuration;
using StockSharp.Messages;
using StockSharp.Algo;
using StockSharp.Algo.Storages;
using StockSharp.Algo.Storages.Csv;
using StockSharp.BusinessEntities;
using StockSharp.Xaml;
public partial class MainWindow
{
private readonly ChannelExecutor _executor;
private bool _isClosing;
private bool _isReleased;
public MainWindow()
{
InitializeComponent();
Instance = this;
Title = Title.Put("Connections with storage");
_executor = TimeSpan.FromSeconds(1).CreateExecutorAndRun(ex => ex.LogError());
}
private Connector MainPanel_OnCreateConnector(string path)
{
//HistoryPath.Folder = path;
var fs = Paths.FileSystem;
var entityRegistry = new CsvEntityRegistry(fs, path, _executor);
var exchangeInfoProvider = new StorageExchangeInfoProvider(entityRegistry);
ConfigManager.RegisterService<IExchangeInfoProvider>(exchangeInfoProvider);
ConfigManager.RegisterService<IBoardMessageProvider>(exchangeInfoProvider);
var storageRegistry = new StorageRegistry(exchangeInfoProvider)
{
DefaultDrive = new LocalMarketDataDrive(fs, path)
};
ConfigManager.RegisterService<IEntityRegistry>(entityRegistry);
ConfigManager.RegisterService<IStorageRegistry>(storageRegistry);
INativeIdStorageProvider nativeIdStorage = new CsvNativeIdStorageProvider(fs, Path.Combine(path, "NativeId"), _executor);
ConfigManager.RegisterService(nativeIdStorage);
var snapshotRegistry = new SnapshotRegistry(fs, Path.Combine(path, "Snapshots"));
return new Connector(entityRegistry.Securities, entityRegistry.PositionStorage, exchangeInfoProvider, storageRegistry, snapshotRegistry, new StorageBuffer());
}
protected override async void OnClosing(CancelEventArgs e)
{
if (_isReleased)
{
base.OnClosing(e);
return;
}
// the window stays open until the queued writes are on the disk
e.Cancel = true;
if (_isClosing)
return;
_isClosing = true;
IsEnabled = false;
try
{
MainPanel.Close();
await _executor.DisposeAsync();
}
finally
{
_isReleased = true;
// a window refuses Close while it is still handling the first attempt to close it
await Dispatcher.Yield();
Close();
}
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
ThemeExtensions.ApplyDefaultTheme();
}
public static MainWindow Instance { get; private set; }
private void HistoryPath_OnFolderChanged(string path)
{
var connector = MainPanel.Connector;
if (connector == null)
return;
connector.Adapter.StorageSettings.Drive = new LocalMarketDataDrive(Paths.FileSystem, path.ToFullPath());
connector.LookupAll();
}
}