Hello Ben,
I have updated your code and tested, it works:
private async Task GetLocalIp() { int timeout = 5000; var cts = new CancellationTokenSource(timeout); var result = string.Empty; var timeoutTask = Task.Run(async () => { await Task.Delay(timeout); result = "Error:Timed Out. A connection could not be found."; }, cts.Token); var scheduledTask = Task.Run( () => { try { var icp = NetworkInformation.GetInternetConnectionProfile(); if (icp?.NetworkAdapter != null) { var hostname = NetworkInformation.GetHostNames().SingleOrDefault(hn => hn.IPInformation?.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId == icp.NetworkAdapter.NetworkAdapterId); result = hostname?.CanonicalName; } } catch(Exception ex) { result = $"Error:{ex.Message}"; } }, cts.Token); await Task.WhenAny(scheduledTask, timeoutTask); cts.Cancel(); await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { IPAdressTextBlock.Text = result; }); }
Even though I don't think this would cause deadlock, you can refer to this blog ant msdn article to understand Deadlocks, it is a better option to use a dynamic variable.
Best Regards,
Michael
MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.