Skip to content

Commit fcedbf9

Browse files
BornToBeRootclaude
andcommitted
Feature: IP Scanner: Max. concurrent Windows host information threads configurable
The max. number of hosts whose NetApi requests run at the same time (was a constant 16) is a setting now (default 16, 1-64). The slots stay shared by all scans; the limit is passed with every request, so a changed value applies to the next requests while blocked calls of earlier scans still count. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 59a04a9 commit fcedbf9

13 files changed

Lines changed: 278 additions & 16 deletions

File tree

‎Source/NETworkManager.Localization/Resources/Strings.Designer.cs‎

Lines changed: 9 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Source/NETworkManager.Localization/Resources/Strings.resx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2003,6 +2003,9 @@ Profile files are not affected!</value>
20032003
<data name="MaxPortThreads" xml:space="preserve">
20042004
<value>Max. concurrent port threads</value>
20052005
</data>
2006+
<data name="MaxWindowsThreads" xml:space="preserve">
2007+
<value>Max. concurrent Windows host information threads</value>
2008+
</data>
20062009
<data name="PowerShell" xml:space="preserve">
20072010
<value>PowerShell</value>
20082011
</data>

‎Source/NETworkManager.Models/Network/IPScanner.cs‎

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -28,16 +28,6 @@ public sealed class IPScanner(IPScannerOptions options)
2828
private readonly bool _isSMBPortScanned =
2929
options.PortScanEnabled && options.PortScanPorts.Contains(SMBInfoResolver.SMBPort);
3030

31-
/// <summary>
32-
/// Max. number of hosts whose NetApi requests run at the same time, in all scans of the application. The calls
33-
/// are blocking and can't be canceled (see <see cref="WindowsNetApiResolver" />): each one has its own thread, a
34-
/// call that exceeds the timeout keeps its slot until Windows returns - also after its scan is completed, so
35-
/// the slots are shared by all scans (tabs, repeated scans), otherwise blocked calls could pile up.
36-
/// </summary>
37-
private const int MaxWindowsThreads = 16;
38-
39-
private static readonly SemaphoreSlim WindowsSemaphore = new(MaxWindowsThreads, MaxWindowsThreads);
40-
4131
// Network logon with the Windows credentials of the profile / group (null: the user running the application) and
4232
// the error if it could not be created (every host gets it instead of using another user)
4333
private WindowsLogon _windowsLogon;
@@ -848,8 +838,9 @@ public static string GetWindowsTarget(IPAddress ipAddress, string dnsHostname, N
848838
}
849839

850840
/// <summary>
851-
/// Runs the blocking NetApi requests of a host on its own thread (max. <see cref="MaxWindowsThreads" /> at the
852-
/// same time) with the network logon of the scan, waits at most the timeout.
841+
/// Runs the blocking NetApi requests of a host on its own thread (max.
842+
/// <see cref="IPScannerOptions.MaxWindowsThreads" /> at the same time in all scans, see
843+
/// <see cref="WindowsNetApiSlots" />) with the network logon of the scan, waits at most the timeout.
853844
/// </summary>
854845
/// <param name="ipAddress">IP address of the host (if the hostname can't be found).</param>
855846
/// <param name="target">Hostname or IP address to connect to, see <see cref="GetWindowsTarget" />.</param>
@@ -932,7 +923,8 @@ void Complete(WindowsNetApiInfo info)
932923

933924
try
934925
{
935-
isSlotFree = await WindowsSemaphore.WaitAsync(timeout, cancellationToken).ConfigureAwait(false);
926+
isSlotFree = await WindowsNetApiSlots.Shared
927+
.WaitAsync(options.MaxWindowsThreads, timeout, cancellationToken).ConfigureAwait(false);
936928
}
937929
catch (OperationCanceledException)
938930
{
@@ -1010,7 +1002,7 @@ WindowsNetApiInfo Resolve()
10101002
{
10111003
hostLogon?.Dispose();
10121004

1013-
WindowsSemaphore.Release();
1005+
WindowsNetApiSlots.Shared.Release();
10141006

10151007
// Not sent or an exception: not decided, the next host checks them (the row shows the error)
10161008
Complete(isSent && !isException ? result : null);

‎Source/NETworkManager.Models/Network/IPScannerOptions.cs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,13 @@ public record IPScannerOptions
1616
/// </summary>
1717
public required int MaxPortThreads { get; init; }
1818

19+
/// <summary>
20+
/// Max. number of hosts whose NetApi requests run at the same time, in all scans of the application (the calls
21+
/// are blocking and keep their thread after the timeout until Windows returns), see
22+
/// <see cref="WindowsNetApiSlots" />.
23+
/// </summary>
24+
public required int MaxWindowsThreads { get; init; }
25+
1926
/// <summary>
2027
/// Ping the host.
2128
/// </summary>
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
using System;
2+
using System.Diagnostics;
3+
using System.Threading;
4+
using System.Threading.Tasks;
5+
6+
namespace NETworkManager.Models.Network;
7+
8+
/// <summary>
9+
/// Slots for the blocking NetApi requests of the IP Scanner, shared by all scans of the application (tabs, repeated
10+
/// scans): a call that exceeds the timeout keeps its slot until Windows returns - also after its scan is completed -
11+
/// so blocked calls can't pile up. Like a semaphore, but the max. number of slots is passed with every request: a
12+
/// changed setting applies to the next request, also while calls of an earlier scan with another limit are still
13+
/// running (a lower limit lets no new call start until enough of them returned).
14+
/// </summary>
15+
public sealed class WindowsNetApiSlots
16+
{
17+
/// <summary>
18+
/// Slots of all scans of the application.
19+
/// </summary>
20+
public static WindowsNetApiSlots Shared { get; } = new();
21+
22+
private readonly Lock _lock = new();
23+
private int _used;
24+
25+
// Completed when a slot is released, then replaced: wakes up all waiting requests, they check the limit again
26+
private TaskCompletionSource _released = new(TaskCreationOptions.RunContinuationsAsynchronously);
27+
28+
/// <summary>
29+
/// Number of slots in use (calls that are running, also after their timeout).
30+
/// </summary>
31+
public int Used
32+
{
33+
get
34+
{
35+
lock (_lock)
36+
return _used;
37+
}
38+
}
39+
40+
/// <summary>
41+
/// Waits for a free slot. Release it with <see cref="Release" /> when the call returned.
42+
/// </summary>
43+
/// <param name="maxSlots">Max. number of slots in use (incl. this one), at least 1.</param>
44+
/// <param name="timeout">Max. time to wait.</param>
45+
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
46+
/// <returns>True if a slot was taken, false after the timeout.</returns>
47+
public async Task<bool> WaitAsync(int maxSlots, TimeSpan timeout, CancellationToken cancellationToken)
48+
{
49+
maxSlots = Math.Max(1, maxSlots);
50+
51+
var stopwatch = Stopwatch.StartNew();
52+
53+
while (true)
54+
{
55+
Task released;
56+
57+
lock (_lock)
58+
{
59+
if (_used < maxSlots)
60+
{
61+
_used++;
62+
63+
return true;
64+
}
65+
66+
released = _released.Task;
67+
}
68+
69+
var remaining = timeout - stopwatch.Elapsed;
70+
71+
if (remaining <= TimeSpan.Zero)
72+
return false;
73+
74+
try
75+
{
76+
await released.WaitAsync(remaining, cancellationToken).ConfigureAwait(false);
77+
}
78+
catch (TimeoutException)
79+
{
80+
return false;
81+
}
82+
}
83+
}
84+
85+
/// <summary>
86+
/// Releases a slot taken with <see cref="WaitAsync" />.
87+
/// </summary>
88+
public void Release()
89+
{
90+
TaskCompletionSource released;
91+
92+
lock (_lock)
93+
{
94+
if (_used == 0)
95+
throw new InvalidOperationException("No slot is in use.");
96+
97+
_used--;
98+
99+
released = _released;
100+
_released = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
101+
}
102+
103+
released.SetResult();
104+
}
105+
}

‎Source/NETworkManager.Settings/GlobalStaticConfiguration.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,7 @@ public static class GlobalStaticConfiguration
159159
public static int IPScanner_PortScanAttempts => 1;
160160
public static int IPScanner_MaxHostThreads => 128;
161161
public static int IPScanner_MaxPortThreads => 16;
162+
public static int IPScanner_MaxWindowsThreads => 16;
162163
public static bool IPScanner_NetBIOSEnabled => true;
163164
public static int IPScanner_NetBIOSTimeout => 2000;
164165
public static bool IPScanner_ARPEnabled => true;

‎Source/NETworkManager.Settings/SettingsInfo.cs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1663,6 +1663,19 @@ public int IPScanner_MaxPortThreads
16631663
}
16641664
} = GlobalStaticConfiguration.IPScanner_MaxPortThreads;
16651665

1666+
public int IPScanner_MaxWindowsThreads
1667+
{
1668+
get;
1669+
set
1670+
{
1671+
if (value == field)
1672+
return;
1673+
1674+
field = value;
1675+
OnPropertyChanged();
1676+
}
1677+
} = GlobalStaticConfiguration.IPScanner_MaxWindowsThreads;
1678+
16661679
public string IPScanner_ExportFilePath
16671680
{
16681681
get;
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
using System;
2+
using System.Threading;
3+
using System.Threading.Tasks;
4+
using NETworkManager.Models.Network;
5+
using Xunit;
6+
7+
namespace NETworkManager.Tests.Network;
8+
9+
/// <summary>
10+
/// Slots of the blocking NetApi requests, shared by all scans: the max. number is passed with every request.
11+
/// </summary>
12+
public class WindowsNetApiSlotsTests
13+
{
14+
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(5);
15+
private static readonly TimeSpan ShortTimeout = TimeSpan.FromMilliseconds(100);
16+
17+
[Fact]
18+
public async Task WaitAsync_TakesSlotsUpToTheLimit()
19+
{
20+
var slots = new WindowsNetApiSlots();
21+
22+
Assert.True(await slots.WaitAsync(2, Timeout, CancellationToken.None));
23+
Assert.True(await slots.WaitAsync(2, Timeout, CancellationToken.None));
24+
Assert.False(await slots.WaitAsync(2, ShortTimeout, CancellationToken.None));
25+
Assert.Equal(2, slots.Used);
26+
}
27+
28+
[Fact]
29+
public async Task WaitAsync_StartsWhenASlotIsReleased()
30+
{
31+
var slots = new WindowsNetApiSlots();
32+
33+
Assert.True(await slots.WaitAsync(1, Timeout, CancellationToken.None));
34+
35+
var waiting = slots.WaitAsync(1, Timeout, CancellationToken.None);
36+
37+
Assert.False(waiting.IsCompleted);
38+
39+
slots.Release();
40+
41+
Assert.True(await waiting);
42+
Assert.Equal(1, slots.Used);
43+
}
44+
45+
[Fact]
46+
public async Task WaitAsync_HigherLimitAppliesWhileSlotsAreUsed()
47+
{
48+
var slots = new WindowsNetApiSlots();
49+
50+
Assert.True(await slots.WaitAsync(1, Timeout, CancellationToken.None));
51+
52+
// E.g. the setting was raised: calls of the earlier scan still count
53+
Assert.True(await slots.WaitAsync(2, Timeout, CancellationToken.None));
54+
Assert.False(await slots.WaitAsync(2, ShortTimeout, CancellationToken.None));
55+
}
56+
57+
[Fact]
58+
public async Task WaitAsync_LowerLimitWaitsUntilEnoughSlotsAreReleased()
59+
{
60+
var slots = new WindowsNetApiSlots();
61+
62+
for (var i = 0; i < 3; i++)
63+
Assert.True(await slots.WaitAsync(3, Timeout, CancellationToken.None));
64+
65+
// E.g. the setting was lowered: no new call until less than 1 slot is used
66+
var waiting = slots.WaitAsync(1, Timeout, CancellationToken.None);
67+
68+
slots.Release();
69+
slots.Release();
70+
71+
await Task.Delay(ShortTimeout);
72+
Assert.False(waiting.IsCompleted);
73+
74+
slots.Release();
75+
76+
Assert.True(await waiting);
77+
Assert.Equal(1, slots.Used);
78+
}
79+
80+
[Fact]
81+
public async Task WaitAsync_Canceled_Throws()
82+
{
83+
var slots = new WindowsNetApiSlots();
84+
85+
Assert.True(await slots.WaitAsync(1, Timeout, CancellationToken.None));
86+
87+
using var cancellationTokenSource = new CancellationTokenSource(ShortTimeout);
88+
89+
await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
90+
slots.WaitAsync(1, Timeout, cancellationTokenSource.Token));
91+
Assert.Equal(1, slots.Used);
92+
}
93+
94+
[Fact]
95+
public void Release_WithoutSlot_Throws()
96+
{
97+
Assert.Throws<InvalidOperationException>(() => new WindowsNetApiSlots().Release());
98+
}
99+
}

‎Source/NETworkManager/ViewModels/IPScannerSettingsViewModel.cs‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -697,6 +697,25 @@ public int MaxPortThreads
697697
}
698698
}
699699

700+
/// <summary>
701+
/// Gets or sets the maximum number of hosts whose Windows host information (NetApi) is read at the same time.
702+
/// </summary>
703+
public int MaxWindowsThreads
704+
{
705+
get;
706+
set
707+
{
708+
if (value == field)
709+
return;
710+
711+
if (!_isLoading)
712+
SettingsManager.Current.IPScanner_MaxWindowsThreads = value;
713+
714+
field = value;
715+
OnPropertyChanged();
716+
}
717+
}
718+
700719
#endregion
701720

702721
#region Constructor, load settings
@@ -769,6 +788,7 @@ private void LoadSettings()
769788
WindowsMaxLogonFailures = SettingsManager.Current.IPScanner_WindowsMaxLogonFailures;
770789
MaxHostThreads = SettingsManager.Current.IPScanner_MaxHostThreads;
771790
MaxPortThreads = SettingsManager.Current.IPScanner_MaxPortThreads;
791+
MaxWindowsThreads = SettingsManager.Current.IPScanner_MaxWindowsThreads;
772792
}
773793

774794
#endregion

‎Source/NETworkManager/ViewModels/IPScannerViewModel.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1412,6 +1412,7 @@ private static IPScannerOptions CreateScanOptions(int[] ports, int[] webPagePort
14121412
{
14131413
MaxHostThreads = SettingsManager.Current.IPScanner_MaxHostThreads,
14141414
MaxPortThreads = SettingsManager.Current.IPScanner_MaxPortThreads,
1415+
MaxWindowsThreads = SettingsManager.Current.IPScanner_MaxWindowsThreads,
14151416
ICMPEnabled = SettingsManager.Current.IPScanner_ICMPEnabled,
14161417
OSGuessEnabled = SettingsManager.Current.IPScanner_OSGuessEnabled,
14171418
ICMPAttempts = SettingsManager.Current.IPScanner_ICMPAttempts,

0 commit comments

Comments
 (0)