I have an async method inside BackgroundService where I need to wait until a specific condition is met within a delegate that can be called multiple times. Here's the code snippet:
private async Task BuyAndSetLimitSellOrder(string pair, CancellationToken cancellationToken)
{
var buyOrder = await BuyAndWriteOrderToDb(pair);
var sellOrder = await SetSellAndWriteOrderToDb(pair, buyOrder);
var handleReceivedMessageToken = new CancellationTokenSource();
var pingDelegate = await _binanceService.SubscribeToUserData(messageHandler: async userData =>
{
await HandleReceivedMessage(userData, sellOrder.Id, handleReceivedMessageToken);
}, cancellationToken);
// Wait here until a specific string is received within the HandleReceivedMessage delegate.
}
In the above code i want to wait until a specific string is received within the HandleReceivedMessage delegate, which can be called multiple times by a WebSocket.
Here is SubscribeToUserData code:
public async Task<Func<Task>> SubscribeToUserData(Func<string, Task> messageHandler, CancellationToken cancellationToken)
{
string response = await _userDataStreams.CreateSpotListenKey();
string listenKey = (System.Text.Json.JsonSerializer.Deserialize<CreateSpotListenKeyResponse>(response) ?? throw new FormatException("Invalid AccountInformation string")).ListenKey;
UserDataWebSocket websocket = new(listenKey, _configuration.BinanceWssBaseUrl);
websocket.OnMessageReceived(messageHandler, CancellationToken.None);
await websocket.ConnectAsync(CancellationToken.None);
return () => PingSpotListenKey(listenKey);
}
I tried multiple things including ManualResetEvent and while loop waiting for canncelation token but anything i put there keep blocking call to HandleReceivedMessage. Also im using binance-connector-dotnet for binance API calls