Merge pull request #12099 from jtattermusch/csharp_shutdownevent

Add GrpcEnvironment.ShuttingDown event
pull/12142/head
Jan Tattermusch 8 years ago committed by GitHub
commit 593a22a95c
  1. 15
      src/csharp/Grpc.Core.Tests/GrpcEnvironmentTest.cs
  2. 17
      src/csharp/Grpc.Core/GrpcEnvironment.cs

@ -18,6 +18,7 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Threading;
using Grpc.Core; using Grpc.Core;
using NUnit.Framework; using NUnit.Framework;
@ -75,5 +76,19 @@ namespace Grpc.Core.Tests
var parts = coreVersion.Split('.'); var parts = coreVersion.Split('.');
Assert.AreEqual(3, parts.Length); Assert.AreEqual(3, parts.Length);
} }
[Test]
public void ShuttingDownEventIsFired()
{
var cts = new CancellationTokenSource();
var handler = new EventHandler((sender, args) => { cts.Cancel(); });
GrpcEnvironment.ShuttingDown += handler;
var env = GrpcEnvironment.AddRef();
GrpcEnvironment.ReleaseAsync().Wait();
GrpcEnvironment.ShuttingDown -= handler;
Assert.IsTrue(cts.Token.IsCancellationRequested);
}
} }
} }

@ -49,7 +49,7 @@ namespace Grpc.Core
readonly DebugStats debugStats = new DebugStats(); readonly DebugStats debugStats = new DebugStats();
readonly AtomicCounter cqPickerCounter = new AtomicCounter(); readonly AtomicCounter cqPickerCounter = new AtomicCounter();
bool isClosed; bool isShutdown;
/// <summary> /// <summary>
/// Returns a reference-counted instance of initialized gRPC environment. /// Returns a reference-counted instance of initialized gRPC environment.
@ -237,6 +237,12 @@ namespace Grpc.Core
} }
} }
/// <summary>
/// Occurs when <c>GrpcEnvironment</c> is about the start the shutdown logic.
/// If <c>GrpcEnvironment</c> is later initialized and shutdown, the event will be fired again (unless unregistered first).
/// </summary>
public static event EventHandler ShuttingDown;
/// <summary> /// <summary>
/// Creates gRPC environment. /// Creates gRPC environment.
/// </summary> /// </summary>
@ -311,13 +317,16 @@ namespace Grpc.Core
/// </summary> /// </summary>
private async Task ShutdownAsync() private async Task ShutdownAsync()
{ {
if (isClosed) if (isShutdown)
{ {
throw new InvalidOperationException("Close has already been called"); throw new InvalidOperationException("ShutdownAsync has already been called");
} }
await Task.Run(() => ShuttingDown?.Invoke(this, null)).ConfigureAwait(false);
await threadPool.StopAsync().ConfigureAwait(false); await threadPool.StopAsync().ConfigureAwait(false);
GrpcNativeShutdown(); GrpcNativeShutdown();
isClosed = true; isShutdown = true;
debugStats.CheckOK(); debugStats.CheckOK();
} }

Loading…
Cancel
Save