C
C#12mo ago
Eistee

❔ ConfigureAwait(false) (IntelliCode Suggestion)

Can someone help me to understand why IntelliCode is suggesting ConfigureAwait(false) at line 16 await Dns.GetHostEntryAsync(ipAddress);? Would this really result in an advantage?
private async Task<List<DeviceInfo>> GetDevices(XDocument xDocument)
{
List<DeviceInfo> deviceList = new List<DeviceInfo>();

var itemElements = xDocument.Descendants("item");
foreach (var itemElement in itemElements)
{
string? deviceName = itemElement.Element("device")?.Value;
string? host = itemElement.Element("host")?.Value;
string? objId = itemElement.Element("objid")?.Value;

if (IPAddress.TryParse(host, out IPAddress? ipAddress) && ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
try
{
var hostEntry = await Dns.GetHostEntryAsync(ipAddress);
host = hostEntry.HostName;
}
catch
{
_logger.LogError($"There is an error occured while resolving {ipAddress}: {host}");
}
}

// remove all possible domains from FQDNs to get hostnames even if they include dots
if (_optionsAccessor.PossibleOccuringDomains is not null && !string.IsNullOrEmpty(host))
{
deviceName = host;
_optionsAccessor.PossibleOccuringDomains.ForEach(item =>
{
deviceName = deviceName.Replace(item, string.Empty);
});
}

deviceList.Add(new DeviceInfo { HostName = deviceName, FQDN = host, ObjID = objId });
}
return deviceList;
}
private async Task<List<DeviceInfo>> GetDevices(XDocument xDocument)
{
List<DeviceInfo> deviceList = new List<DeviceInfo>();

var itemElements = xDocument.Descendants("item");
foreach (var itemElement in itemElements)
{
string? deviceName = itemElement.Element("device")?.Value;
string? host = itemElement.Element("host")?.Value;
string? objId = itemElement.Element("objid")?.Value;

if (IPAddress.TryParse(host, out IPAddress? ipAddress) && ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
try
{
var hostEntry = await Dns.GetHostEntryAsync(ipAddress);
host = hostEntry.HostName;
}
catch
{
_logger.LogError($"There is an error occured while resolving {ipAddress}: {host}");
}
}

// remove all possible domains from FQDNs to get hostnames even if they include dots
if (_optionsAccessor.PossibleOccuringDomains is not null && !string.IsNullOrEmpty(host))
{
deviceName = host;
_optionsAccessor.PossibleOccuringDomains.ForEach(item =>
{
deviceName = deviceName.Replace(item, string.Empty);
});
}

deviceList.Add(new DeviceInfo { HostName = deviceName, FQDN = host, ObjID = objId });
}
return deviceList;
}
18 Replies
chef drone builder
It would increase performance, but unless you know exactly what it is doing, i would nod recommend it.
Playboi17
Playboi1712mo ago
It wouldn’t increase performance. It would change the synchronization context that the callback uses.
chef drone builder
Yes, but to change the synchronisation context takes a bit of time, so not doing it increases performance If you actually have one, which is only really the case in gui applications
Playboi17
Playboi1712mo ago
I guess your right
mtreit
mtreit12mo ago
The suggestion has little to do with performance. It's a best practice to always use ConfigureAwait(false) if you are writing code in a library that does not need to capture the syncrhonization context. It avoids the possibility of deadlocks if some consumer of your code decides to call .Result or .Wait (which is usually a poor practice, but it happens in the real world all the time.)
chef drone builder
I would disagree, microsoft themself say that the reason is performance and deadlock related: https://devblogs.microsoft.com/dotnet/configureawait-faq/
Stephen Toub - MSFT
.NET Blog
ConfigureAwait FAQ - .NET Blog
.NET added async/await to the languages and libraries over seven years ago. In that time, it’s caught on like wildfire, not only across the .NET ecosystem, but also being replicated in a myriad of other languages and frameworks. It’s also seen a ton of improvements in .NET,
mtreit
mtreit12mo ago
I'm familiar with that post and I agree with everything in it. Just that performance is not the primary reason to use ConfigureAwait(false)...
chef drone builder
Ok, i see
mtreit
mtreit12mo ago
I wonder if I have a benchmark for this...
chef drone builder
Depends 100% on what the synchronisation context actually does.
mtreit
mtreit12mo ago
Ah yes, I do
chef drone builder
This is a console app, it doesnt even have a synchronisation context, or am im I missing something
mtreit
mtreit12mo ago
It has the default synchronization context (which is the thread pool) It's entirely possible that it's a noop for the default task scheduler I never checked Although the benchmark numbers do seem to show that ConfigureAwait(true) has some small overhead
mtreit
mtreit12mo ago
mtreit
mtreit12mo ago
Congratulations @kocha you have lead me down a complete rabbit hole: https://discord.com/channels/143867839282020352/143867839282020352/1133887368131264532
MODiX
MODiX12mo ago
mtreit
public long ReadAsyncAwaitCustomContextConfigureAwaitFalse()
{
long result = 0;

using var sr = new StreamReader(_testFile);

string line;

while ((line = AsyncContext.Run(async () => { var res = await sr.ReadLineAsync().ConfigureAwait(false); Console.WriteLine($"{res} -> {SynchronizationContext.Current?.GetType().Name ?? "<null>"}"); return res; })) != null)
{
result += int.Parse(line);
}

return result;
}
public long ReadAsyncAwaitCustomContextConfigureAwaitFalse()
{
long result = 0;

using var sr = new StreamReader(_testFile);

string line;

while ((line = AsyncContext.Run(async () => { var res = await sr.ReadLineAsync().ConfigureAwait(false); Console.WriteLine($"{res} -> {SynchronizationContext.Current?.GetType().Name ?? "<null>"}"); return res; })) != null)
{
result += int.Parse(line);
}

return result;
}
I have a two line file. Literally these bytes:
Offset Bytes Ascii
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
------ ----------------------------------------------- -----
0000000000000000 30 0D 0A 31 0D 0A 0��1��
Offset Bytes Ascii
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
------ ----------------------------------------------- -----
0000000000000000 30 0D 0A 31 0D 0A 0��1��
If I feed this file to the above code, what does it print out?
Quoted by
<@406536255426396160> from #chat (click here)
React with ❌ to remove this embed.
Accord
Accord12mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts
✅ Class as a field?Suppose I have Class1, Class2, and Class3. Class2 is just a container of information. At runtime I w❔ Lazily evaluating Dictionary in update loop with good performance## Situation I have an update loop which receives some data which is Dictionary-like. Due to a versi❔ Hello everyone, I'm creating an application with ASP.NET Core,Hello everyone, I'm creating an application with ASP.NET Core, I used to insert images by typing the❔ App resource files conventionWhen your app depends on files you read from disk, what's the convention for where to store them? Fo❔ NSubstitute on IEnumerableHey - I'm trying to "freeze" an `IEnumerable<>` and return a mocked enumerator However, when doinmg❔ how do i include a range of numbers into a reply like 1-1000 for my thingstring correct = "well done. "; string wrong = "nope.try again. "; Console.WriteLine("Hello."); ❔ Xamarin.Forms Android App problem using Application.Context.StartActivity(intent)Hi, in short, I created a super small Xamarin.Forms Android App. All I need is just to press a butto❔ How can I test a custom IValueResolver in AutoMapper 12?With the latest release of AutoMapper,the public constructor in the ResolutionContext class has been✅ hey am a student and i need to pass exams without learning anybody helphey am a student and i need to pass exams without learning anybody helpReal-time audio recording and streamingHey, so I'm trying to make a home assistant like console app, but I'm having issues with the voice r