Skip to content
New issue

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

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

Already on GitHub? # to your account

Thread safe ID generation #218

Merged
merged 4 commits into from
Mar 11, 2024
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
11 changes: 10 additions & 1 deletion src/DnsClient/DnsRequestHeader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ namespace DnsClient
{
internal class DnsRequestHeader
{
#if !NET6_0_OR_GREATER
private static readonly Random s_random = new Random();
#endif
public const int HeaderLength = 12;
private ushort _flags = 0;

Expand Down Expand Up @@ -102,7 +104,14 @@ public void RefreshId()

private static ushort GetNextUniqueId()
{
return (ushort)s_random.Next(1, ushort.MaxValue);
#if NET6_0_OR_GREATER
return (ushort)Random.Shared.Next(1, ushort.MaxValue);
#else
lock (s_random)
{
return (ushort)s_random.Next(1, ushort.MaxValue);
}
#endif
}
}
}
20 changes: 18 additions & 2 deletions test/DnsClient.Tests/DnsRequestHeaderTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using Xunit;

namespace DnsClient.Tests
Expand Down Expand Up @@ -49,5 +50,20 @@ public void DnsRequestHeader_ChangeRecursion()

Assert.Equal(DnsOpCode.Notify, header.OpCode);
}

[Fact]
public void DnsRequestHeader_IdIsPseudoUnique()
{
ConcurrentDictionary<int, int> ids = new ConcurrentDictionary<int, int>();

Parallel.For(0, 1000, i =>
{
var header = new DnsRequestHeader(DnsOpCode.Query);
Assert.NotEqual(0, header.Id);
ids.TryAdd(header.Id, 0);
});

Assert.True(ids.Count > 950, $"Only {ids.Count} of 1000 ids are unique!");
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without the change the number of collisions is significantly higher.

}
}
}
}