I am experiencing an unhandled exception which, as per my understanding, occurs when a task is cancelled before it is completed. However, in my code, I am not cancelling any tasks. I have added try-catch blocks and multiple handlers, but I am still unable to find the issue. The crash happens randomly and there are no fixed steps leading up to it.
Error
Application: AlgoOrderPlacement.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Threading.Tasks.TaskCanceledException
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
at SocketIOClient.Transport.HttpTransport+<SendAsync>d__13.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
at SocketIOClient.Transport.TransportRouter+<ConnectByPollingAsync>d__43.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
at SocketIOClient.Transport.TransportRouter+<ConnectAsync>d__41.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
at SocketIOClient.SocketIO+<ConnectAsync>d__81.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at SocketIOClient.SocketIO+<ConnectAsync>d__81.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
at SocketIOClient.SocketIO+<InvokeDisconnect>d__105.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
namespace AlgoOrderManagement.Helper
{
public class OrderSocketConnection
{
protected SocketIO Socket { get; set; } = null;
long lastSocketSequence = 0;
public Dictionary<string, OrderData> OrderStatusDetails = new Dictionary<string, OrderData>();
private User currentUser = null;
public delegate void SocketStatus(bool status);
public event SocketStatus SocketStatusUpdate;
string URL = string.Empty;
public void StartSocket(User user, string URL)
{
this.currentUser = user;
this.URL = URL;
_ = StartSocketAsync();
}
private async Task StartSocketAsync()
{
try
{
if (this.Socket != null)
{
UnSubscribeToConnectionEvents();
}
if (this.Socket != null)
{
this.Socket?.DisconnectAsync();
this.Socket?.Dispose();
}
this.Socket = new SocketIO(URL, new SocketIOOptions
{
Query = new Dictionary<string, string>() { { "token", currentUser.TOKEN }, { "userID", currentUser.USERID }, { "apiType", "INTERACTIVE" } },
EIO = 3,
Transport = SocketIOClient.Transport.TransportProtocol.Polling,
Path = "/interactive/socket.io"
});
SubscribeToConnectionEvents();
FileLogger.logMessage(currentUser.USERNAME + " Before StartSocket");
await this.Socket.ConnectAsync();
FileLogger.logMessage(currentUser.USERNAME + " After StartSocket");
}
catch (Exception ex)
{
FileLogger.logMessage("User StartSocket EX = " + ex.Message + ex.StackTrace);
await Task.Delay(5000);
_ = StartSocketAsync();
}
}
private void Socket_OnReconnecting(object sender, int e)
{
FileLogger.logMessage(currentUser.USERNAME + " SOCKET SUCCESS= " + e, currentUser.USERNAME);
}
private void Socket_OnDisconnected(object sender, string e)
{
FileLogger.logMessage(currentUser.USERNAME + " SOCKET DIS-CONNECT= " + e, currentUser.USERNAME);
UpdateUISocketStatus(false);
}
private void Socket_OnPong(object sender, TimeSpan e)
{
}
private void Socket_OnPing(object sender, EventArgs e)
{
}
private void Socket_OnConnected(object sender, EventArgs e)
{
FileLogger.logMessage(currentUser.USERNAME + " SOCKET SUCCESS= " + e, currentUser.USERNAME);
}
private void OrderUpdate(object order)
{
try
{
dynamic data = JObject.Parse(order.ToString());
if (data != null)
{
if (data.SequenceNumber.Value > lastSocketSequence)
{
lastSocketSequence = data.SequenceNumber.Value;
OrderData orderData = new OrderData();
orderData.orderID = data.AppOrderID;
orderData.order_status = data.OrderStatus;
orderData.cancelRejectReason = data.CancelRejectReason;
orderData.order_execute_price = data.OrderAverageTradedPrice;
orderData.quantity = data.CumulativeQuantity;
orderData.instrument_token = data.ExchangeInstrumentID;
orderData.lastUpdateTime = DateTime.Now;
if (OrderStatusDetails.ContainsKey(orderData.orderID))
{
OrderStatusDetails[orderData.orderID] = orderData;
}
else
{
OrderStatusDetails.Add(orderData.orderID, orderData);
}
}
CheckCancelOrder(data);
}
}
catch (Exception ex)
{
FileLogger.logMessage("OrderUpdate EX = " + ex.Message + ex.StackTrace, currentUser.USERNAME);
}
}
private void CheckCancelOrder(dynamic data)
{
try
{
string orderStatus = data.OrderStatus.ToString();
string cancelRejectReason = data.CancelRejectReason.ToString();
string orderGeneratedDateTimeAPI = data.LastUpdateDateTimeAPI.ToString();
if (orderStatus.ToLower().Equals("cancelled".ToLower()))
{
TelegramSend.SendError(currentUser.USERNAME + " = Order Cancelled Please Check Once = "
+ data.CancelRejectReason + Environment.NewLine +
"TIME = " + orderGeneratedDateTimeAPI);
}
}
catch (Exception ex)
{
}
}
private bool SubscribeToConnectionEvents()
{
if (this.Socket == null)
return false;
this.Socket.On("joined", (data) =>
{
FileLogger.logMessage(" SOCKET JOINED= " + data, currentUser.USERNAME);
UpdateUISocketStatus(true);
});
this.Socket.On("success", (data) =>
{
FileLogger.logMessage(" SOCKET SUCCESS= " + data, currentUser.USERNAME);
});
this.Socket.On("warning", (data) =>
{
FileLogger.logMessage(" SOCKET WARNING= " + data, currentUser.USERNAME);
});
this.Socket.On("error", (data) =>
{
FileLogger.logMessage(" SOCKET ERROR= " + data, currentUser.USERNAME);
UpdateUISocketStatus(false);
});
this.Socket.On("logout", (data) =>
{
FileLogger.logMessage(currentUser.USERNAME + " SOCKET LOGOUT= " + data, currentUser.USERNAME);
UpdateUISocketStatus(false);
});
this.Socket.On("order", (order) =>
{
OrderUpdate(order.GetValue<string>());
FileLogger.logMessage(currentUser.USERNAME + " SOCKET ORDER = " + order.ToString(), currentUser.USERNAME);
});
this.Socket.On("trade", (trade) =>
{
OrderUpdate(trade.GetValue<string>());
FileLogger.logMessage(currentUser.USERNAME + " SOCKET TRADE = " + trade.ToString(), currentUser.USERNAME);
});
this.Socket.OnConnected += Socket_OnConnected;
this.Socket.OnPing += Socket_OnPing;
this.Socket.OnPong += Socket_OnPong;
this.Socket.OnDisconnected += Socket_OnDisconnected;
this.Socket.OnReconnectAttempt += Socket_OnReconnecting;
return true;
}
private void UnSubscribeToConnectionEvents()
{
if (this.Socket != null)
{
this.Socket?.Off("logout");
this.Socket?.Off("error");
this.Socket?.Off("warning");
this.Socket?.Off("success");
this.Socket?.Off("joined");
this.Socket?.Off("order");
this.Socket?.Off("trade");
this.Socket.OnConnected -= Socket_OnConnected;
this.Socket.OnPing -= Socket_OnPing;
this.Socket.OnPong -= Socket_OnPong;
this.Socket.OnDisconnected -= Socket_OnDisconnected;
this.Socket.OnReconnectAttempt -= Socket_OnReconnecting;
}
}
private void UpdateUISocketStatus(bool status)
{
try
{
SocketStatusUpdate?.Invoke(status);
if (status == false)
{
TelegramSend.SendError(currentUser.USERNAME + " Socekt Disconnected ");
}
}
catch (Exception ex)
{
FileLogger.logMessage("User UpdateUISocketStatus EX = " + ex.Message + ex.StackTrace, currentUser.USERNAME);
}
}
}
}