Skip to content

Respect Process.SynchronizingObject in Process events #37308

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1083,7 +1083,14 @@ protected void OnExited()
EventHandler? exited = _onExited;
if (exited != null)
{
exited(this, EventArgs.Empty);
if (SynchronizingObject is ISynchronizeInvoke syncObj && syncObj.InvokeRequired)
{
syncObj.BeginInvoke(exited, new object[] { this, EventArgs.Empty });
}
else
{
exited(this, EventArgs.Empty);
}
}
}

Expand Down Expand Up @@ -1571,8 +1578,16 @@ internal void OutputReadNotifyUser(string? data)
DataReceivedEventHandler? outputDataReceived = OutputDataReceived;
if (outputDataReceived != null)
{
// Call back to user informing data is available
DataReceivedEventArgs e = new DataReceivedEventArgs(data);
outputDataReceived(this, e); // Call back to user informing data is available
if (SynchronizingObject is ISynchronizeInvoke syncObj && syncObj.InvokeRequired)
{
syncObj.Invoke(outputDataReceived, new object[] { this, e });
}
else
{
outputDataReceived(this, e);
}
}
}

Expand All @@ -1582,8 +1597,16 @@ internal void ErrorReadNotifyUser(string? data)
DataReceivedEventHandler? errorDataReceived = ErrorDataReceived;
if (errorDataReceived != null)
{
// Call back to user informing data is available.
DataReceivedEventArgs e = new DataReceivedEventArgs(data);
errorDataReceived(this, e); // Call back to user informing data is available.
if (SynchronizingObject is ISynchronizeInvoke syncObj && syncObj.InvokeRequired)
{
syncObj.Invoke(errorDataReceived, new object[] { this, e });
}
else
{
errorDataReceived(this, e);
}
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.ComponentModel;

namespace System.Diagnostics.Tests
{
internal sealed class DelegateSynchronizeInvoke : ISynchronizeInvoke
{
public Func<bool> InvokeRequiredDelegate;
public Func<Delegate, object[], IAsyncResult> BeginInvokeDelegate;
public Func<Delegate, object[], object> InvokeDelegate;

public bool InvokeRequired => InvokeRequiredDelegate();
public IAsyncResult BeginInvoke(Delegate method, object[] args) => BeginInvokeDelegate(method, args);
public object EndInvoke(IAsyncResult result) => null;
public object Invoke(Delegate method, object[] args) => InvokeDelegate(method, args);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,37 @@ public void TestAsyncErrorStream()
}
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestAsyncErrorStream_SynchronizingObject(bool invokeRequired)
{
StringBuilder sb = new StringBuilder();
int invokeCalled = 0;

Process p = CreateProcessPortable(RemotelyInvokable.ErrorProcessBody);
p.SynchronizingObject = new DelegateSynchronizeInvoke()
{
InvokeRequiredDelegate = () => invokeRequired,
InvokeDelegate = (d, args) =>
{
invokeCalled++;
return d.DynamicInvoke(args);
}
};
p.StartInfo.RedirectStandardError = true;
p.ErrorDataReceived += (s, e) => sb.Append(e.Data);
p.Start();
p.BeginErrorReadLine();

Assert.True(p.WaitForExit(WaitInMS));
p.WaitForExit(); // This ensures async event handlers are finished processing.

const string Expected = RemotelyInvokable.TestConsoleApp + " started error stream" + RemotelyInvokable.TestConsoleApp + " closed error stream";
Assert.Equal(Expected, sb.ToString());
Assert.Equal(invokeRequired ? 3 : 0, invokeCalled);
}

[Fact]
public void TestSyncOutputStream()
{
Expand Down Expand Up @@ -491,6 +522,47 @@ public void TestManyOutputLines()
Assert.Equal(ExpectedLineCount + 1, totalLinesReceived);
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestManyOutputLines_SynchronizingObject(bool invokeRequired)
{
const int ExpectedLineCount = 144;

int nonWhitespaceLinesReceived = 0;
int totalLinesReceived = 0;
int invokeCalled = 0;

Process p = CreateProcessPortable(RemotelyInvokable.Write144Lines);
p.SynchronizingObject = new DelegateSynchronizeInvoke()
{
InvokeRequiredDelegate = () => invokeRequired,
InvokeDelegate = (d, args) =>
{
invokeCalled++;
return d.DynamicInvoke(args);
}
};
p.StartInfo.RedirectStandardOutput = true;
p.OutputDataReceived += (s, e) =>
{
if (!string.IsNullOrWhiteSpace(e.Data))
{
nonWhitespaceLinesReceived++;
}
totalLinesReceived++;
};
p.Start();
p.BeginOutputReadLine();

Assert.True(p.WaitForExit(WaitInMS));
p.WaitForExit(); // This ensures async event handlers are finished processing.

Assert.Equal(ExpectedLineCount, nonWhitespaceLinesReceived);
Assert.Equal(ExpectedLineCount + 1, totalLinesReceived);
Assert.Equal(invokeRequired ? totalLinesReceived : 0, invokeCalled);
}

[Fact]
[SkipOnCoreClr("Avoid asserts in FileStream.Read when concurrently disposed", ~RuntimeConfiguration.Release)]
public void TestClosingStreamsAsyncDoesNotThrow()
Expand Down
36 changes: 36 additions & 0 deletions src/libraries/System.Diagnostics.Process/tests/ProcessTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,42 @@ public void TestEnableRaiseEvents(bool? enable)
}
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestExited_SynchronizingObject(bool invokeRequired)
{
bool exitedInvoked = false;
Task beginInvokeTask = null;

Process p = CreateProcessLong();
p.SynchronizingObject = new DelegateSynchronizeInvoke()
{
InvokeRequiredDelegate = () => invokeRequired,
BeginInvokeDelegate = (d, args) =>
{
Assert.Null(beginInvokeTask);
beginInvokeTask = Task.Run(() => d.DynamicInvoke(args));
return beginInvokeTask;
}
};
p.EnableRaisingEvents = true;
p.Exited += delegate { exitedInvoked = true; };
StartSleepKillWait(p);

if (invokeRequired)
{
Assert.NotNull(beginInvokeTask);
beginInvokeTask.Wait();
}
else
{
Assert.Null(beginInvokeTask);
}

Assert.True(exitedInvoked);
}

[Fact]
public void ProcessStart_TryExitCommandAsFileName_ThrowsWin32Exception()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
Link="Common\System\ShouldNotBeInvokedException.cs" />
<Compile Include="$(CommonTestPath)Microsoft\Win32\TempRegistryKey.cs"
Link="Common\Microsoft\Win32\TempRegistryKey.cs" />
<Compile Include="DelegateSynchronizeInvoke.cs" />
<Compile Include="Helpers.cs" />
<Compile Include="Interop.cs" />
<Compile Include="Interop.Unix.cs" Condition="'$(TargetsWindows)' != 'true'" />
Expand Down