reqIds hangs when recereating IBClient - EWrapper


 

I have IBClient that implements EWrapper that I copied from C# samples from official TWS repository. 
When some event happens, I would like to destroy existing client and create new instance. 
This is the method I use to create this client. 
 
void Create()
{
  var signal = new EReaderMonitorSignal();
  _client = new IBClient(signal);
  _client.ClientSocket.SetConnectOptions("+PACEAPI");
  _client.ClientSocket.eConnect(Host, Port, 0);
  var reader = new EReader(_client.ClientSocket, signal);
  var process = new Thread(() =>
  {
    while (_client.ClientSocket.IsConnected())
    {
      signal.waitForSignal();
      reader.processMsgs();
    }
  });
  process.Start();
  reader.Start();
}
 
After that, I'm waiting for the next valid ID.
 
async Task Register()
{
  var source = new TaskCompletionSource();
  void subscribe(int o)
  {
    _client.NextValidId -= subscribe;
    source.TrySetResult();
  }
  _client.NextValidId += subscribe;
  _client.ClientSocket.reqIds(-1);
  await source.Task;
}
 
Then use method to destroy client. 
 
void Destroy()
{
  _client?.ClientSocket?.eDisconnect();
}
 
The first time everything works fine.
When I try to call these 3 methods next time, "reqIds" hangs and I never receive response for "NextValidId". 
Is it some known limitation that only one client can connect to TWS only once or am I missing something? 


 

Each time when you connect you apparently use client ID zero: eConnect(Host, Port, 0). When you disconnect this client you must allow IBKR time to close all processes related to this client on their side. According to an undocumented recommendation from IBKR do you need to wait approximately one minute before you try to connect again to the same client ID number (zero, in your case). Your post does not mention how long you are waiting after closing before trying to reconnect to that client.
If you can't wait one minute before reconnecting then you should simply use a different client ID number. Any integer number can be used, there are no rules for this. So you could use for example a randomly generated ID, or a timestamp as ID (e.g. hhmmss). It is documented that you can have a maximum of 32 clients connected at the same time.