Skip to content

Commit

Permalink
change PortReserver to use ConcurrentDictionary (#3316)
Browse files Browse the repository at this point in the history
* change PortReserver to use ConcurrentDictionary

* update Copyright header and license notice
  • Loading branch information
heng-liu authored Mar 27, 2020
1 parent e0ce7db commit 1f8cd7c
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions test/TestUtilities/Test.Utility/TestServer/PortReserver.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
Expand All @@ -20,6 +22,7 @@ namespace NuGet.Test.Server
/// </summary>
public class PortReserver
{
private static ConcurrentDictionary<string, bool> PortLock = new ConcurrentDictionary<string, bool>();
private readonly int _basePort;

public PortReserver(int basePort = 50231)
Expand Down Expand Up @@ -57,21 +60,26 @@ public async Task<T> ExecuteAsync<T>(

// WaitForLockAsync prevents port contention with this app.
string portLockName = $"NuGet-Port-{port}";
var tryOnceCts = new CancellationTokenSource(TimeSpan.Zero);

try
{
var attemptedPort = port;
return await ConcurrencyUtilities.ExecuteWithFileLockedAsync<T>(
portLockName,
t => action(attemptedPort, token),
tryOnceCts.Token);
if (PortLock.TryAdd(portLockName, true))
{
// Run the action within the lock
return await action(port, token);
}
}
catch (OverflowException)
{
throw;
}
catch (OperationCanceledException)
finally
{
PortLock.TryRemove(portLockName, out _);
}
}
}

private static bool IsTcpPortAvailable(int port)
{
var tcpListener = new TcpListener(IPAddress.Loopback, port);
Expand Down

0 comments on commit 1f8cd7c

Please sign in to comment.