Skip to content

Commit

Permalink
Fix race condition in ServiceProcess tests (#59676)
Browse files Browse the repository at this point in the history
  • Loading branch information
ericstj authored Sep 28, 2021
1 parent cb78a89 commit da358db
Showing 1 changed file with 6 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public TestService(string serviceName, Exception throwException = null)
this._serverStream = new NamedPipeServerStream(serviceName);
_waitClientConnect = this._serverStream.WaitForConnectionAsync();
_waitClientConnect = _waitClientConnect.ContinueWith(_ => DebugTrace("TestService " + ServiceName + ": Connected"));
_waitClientConnect.ContinueWith(t => WriteStreamAsync(PipeMessageByteCode.Connected));
_waitClientConnect = _waitClientConnect.ContinueWith(t => WriteStreamAsync(PipeMessageByteCode.Connected, waitForConnect: false));
DebugTrace("TestService " + ServiceName + ": Ctor completed");
}

Expand Down Expand Up @@ -99,19 +99,19 @@ protected override void OnStop()
{
DebugTrace("TestService " + ServiceName + ": OnStop");
base.OnStop();
WriteStreamAsync(PipeMessageByteCode.Stop).Wait();
// We may be stopping because the test has completed and we're cleaning up the test service so there's no client at all, so don't waitForConnect.
// Tests that verify "Stop" itself should ensure the client connection has completed before calling stop, by waiting on some other message from the pipe first.
WriteStreamAsync(PipeMessageByteCode.Stop, waitForConnect:false).Wait();
}

public async Task WriteStreamAsync(PipeMessageByteCode code, int command = 0)
public async Task WriteStreamAsync(PipeMessageByteCode code, int command = 0, bool waitForConnect = true)
{
DebugTrace("TestService " + ServiceName + ": WriteStreamAsync writing " + code.ToString());

var toWrite = (code == PipeMessageByteCode.OnCustomCommand) ? new byte[] { (byte)command } : new byte[] { (byte)code };

// Wait for the client connection before writing to the pipe.
// Exception: if it's a Stop message, it may be because the test has completed and we're cleaning up the test service so there's no client at all.
// Tests that verify "Stop" itself should ensure the client connection has completed before calling stop, by waiting on some other message from the pipe first.
if (code != PipeMessageByteCode.Stop)
if (waitForConnect)
{
await _waitClientConnect;
}
Expand Down

0 comments on commit da358db

Please sign in to comment.