Clean up if an exception is thrown in the middle of ServerFactory.Start

This commit is contained in:
Stephen Halter 2015-08-25 12:41:11 -07:00
parent c50aec1729
commit 1584d70e1f
1 changed files with 32 additions and 18 deletions

View File

@ -36,13 +36,27 @@ namespace Microsoft.AspNet.Server.Kestrel
public IDisposable Start(IFeatureCollection serverFeatures, Func<IFeatureCollection, Task> application) public IDisposable Start(IFeatureCollection serverFeatures, Func<IFeatureCollection, Task> application)
{ {
var disposables = new List<IDisposable>(); var disposables = new Stack<IDisposable>();
var disposer = new Disposable(() =>
{
foreach (var disposable in disposables)
{
disposable.Dispose();
}
});
try
{
var information = (KestrelServerInformation)serverFeatures.Get<IKestrelServerInformation>(); var information = (KestrelServerInformation)serverFeatures.Get<IKestrelServerInformation>();
var engine = new KestrelEngine(_libraryManager, _appShutdownService); var engine = new KestrelEngine(_libraryManager, _appShutdownService);
disposables.Push(engine);
engine.Start(information.ThreadCount == 0 ? 1 : information.ThreadCount); engine.Start(information.ThreadCount == 0 ? 1 : information.ThreadCount);
foreach (var address in information.Addresses) foreach (var address in information.Addresses)
{ {
disposables.Add(engine.CreateServer( disposables.Push(engine.CreateServer(
address.Scheme, address.Scheme,
address.Host, address.Host,
address.Port, address.Port,
@ -52,14 +66,14 @@ namespace Microsoft.AspNet.Server.Kestrel
await application.Invoke(request.Features).ConfigureAwait(false); await application.Invoke(request.Features).ConfigureAwait(false);
})); }));
} }
disposables.Add(engine);
return new Disposable(() => return disposer;
}
catch
{ {
foreach (var disposable in disposables) disposer.Dispose();
{ throw;
disposable.Dispose(); }
}
});
} }
} }
} }