private static void ResolveCallback(object context) { DnsResolveAsyncResult result = (DnsResolveAsyncResult)context; IPHostEntry hostEntry; try { if (result.IpAddress != null) { hostEntry = InternalGetHostByAddress(result.IpAddress); } else { hostEntry = InternalGetHostByName(result.HostName); } } catch (OutOfMemoryException) { throw; } catch (Exception exception) { result.InvokeCallback(exception); return; } result.InvokeCallback(hostEntry); }
// Helpers for async GetHostByName, ResolveToAddresses, and Resolve - they're almost identical // If hostName is an IPString and justReturnParsedIP==true then no reverse lookup will be attempted, but the original address is returned. private static IAsyncResult HostResolutionBeginHelper(string hostName, bool justReturnParsedIp, bool throwOnIIPAny, AsyncCallback requestCallback, object state) { if (hostName == null) { throw new ArgumentNullException(nameof(hostName)); } if (NetEventSource.IsEnabled) { NetEventSource.Info(null, hostName); } // See if it's an IP Address. IPAddress ipAddress; DnsResolveAsyncResult asyncResult; if (IPAddress.TryParse(hostName, out ipAddress)) { if (throwOnIIPAny && (ipAddress.Equals(IPAddress.Any) || ipAddress.Equals(IPAddress.IPv6Any))) { throw new ArgumentException(SR.net_invalid_ip_addr, nameof(hostName)); } asyncResult = new DnsResolveAsyncResult(ipAddress, null, state, requestCallback); if (justReturnParsedIp) { IPHostEntry hostEntry = NameResolutionUtilities.GetUnresolvedAnswer(ipAddress); asyncResult.StartPostingAsyncOp(false); asyncResult.InvokeCallback(hostEntry); asyncResult.FinishPostingAsyncOp(); return(asyncResult); } } else { asyncResult = new DnsResolveAsyncResult(hostName, null, state, requestCallback); } // Set up the context, possibly flow. asyncResult.StartPostingAsyncOp(false); // If the OS supports it and 'hostName' is not an IP Address, resolve the name asynchronously // instead of calling the synchronous version in the ThreadPool. if (NameResolutionPal.SupportsGetAddrInfoAsync && ipAddress == null) { ValidateHostName(hostName); NameResolutionPal.GetAddrInfoAsync(asyncResult); } else { // Start the resolve. Task.Factory.StartNew( s => ResolveCallback(s), asyncResult, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } // Finish the flowing, maybe it completed? This does nothing if we didn't initiate the flowing above. asyncResult.FinishPostingAsyncOp(); return(asyncResult); }