vdemydiuk / mtapi

MetaTrader API (terminal bridge)
http://mtapi4.net/
MIT License
524 stars 283 forks source link

connection and disconnection synchronization problem #245

Closed nika90426 closed 3 years ago

nika90426 commented 3 years ago

Hi, thanks for nice project! I found BeginConnect(), BeginDisconnect() function have a synchronization problem when they are each called from different thread. BeginConnection() caused MtConnectionException on this line in MtApiClient.cs (SendCommand in details)

        if (client == null)
        {
            throw new MtConnectionException("No connection");
        }

After some debugging, I found its because of connect() and disconnect() are not fully synchronized. This shows the part of connect() function

        ConnectionStateChanged?.Invoke(this, new MtConnectionEventArgs(state, message));

       if (state == MtConnectionState.Connected)
        {
            OnConnected(); // lock guard already released, this causes exception in IsTesting() or BacktestingReady()
        }

After all I resolved it by moving the function call to the earlier line in the lock guard like this.

       if (state == MtConnectionState.Connected)
            {
                _client = client;
                _client.QuoteAdded += _client_QuoteAdded;
                _client.QuoteRemoved += _client_QuoteRemoved;
                _client.QuoteUpdated += _client_QuoteUpdated;
                _client.ServerDisconnected += _client_ServerDisconnected;
                _client.ServerFailed += _client_ServerFailed;
                _client.MtEventReceived += _client_MtEventReceived;
                message = string.IsNullOrEmpty(client.Host) ? $"Connected to localhost:{client.Port}" : $"Connected to  { client.Host}:{client.Port}";

                OnConnected(); // Moved from below line
            }

            _connectionState = state;

I hope this might help you. Thank you!

lazou commented 3 years ago

Hi @nika90426, maybe you could provide a PR with your proposal? I think that would be helpfull :)

vdemydiuk commented 3 years ago

@nika90426 Hi. Thank you for your feedback. If it is possible please make PR for the fix.

nika90426 commented 3 years ago

I've observed this issue for a while, and finally I find that I was wrong. I'm sorry for my mistake, and thank you for nice project again!