lock SendData to fix random connection failures #1623
                
     Merged
            
            
          
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Fixes #1253 and probably #1493 .
This adds a lock to SendData to avoid the loop to interleave between multiple messages, causing a "bad message" error in the server (see #1253 (comment)).
This may totally be the wrong fix since I'm not really familiar with the protocol and I couldn't find anything specifically about this in the RFCs. But it seems sensible to me that the server doesn't expect this to happen.
By adding some logging I confirmed that in the failure cases of the test, the loop did indeed interleave between different messages. In the success cases, there simply were never more than 1 iteration, so it couldn't interleave.
Without this fix, I had the test fail about every third run. With this fix, I have run the test for about 500 times without a failure.