public MainPage() { this.InitializeComponent(); GetLocalIp().ConfigureAwait(false); } private async Task GetLocalIp() { int timeout = 1000; var timeouttask = Task.Run(async () => { await Task.Delay(timeout); await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { IPAdressTextBlock.Text = "Error:Timed Out. A connection could not be found."; }); }); var task = Task.Run( async () => { 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); await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { IPAdressTextBlock.Text = hostname?.CanonicalName; }); } } catch { await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { IPAdressTextBlock.Text = "Network not found."; }); } }); await Task.WhenAny(task, timeouttask); }
I changed the code because this does not update the textbox in the GUI in the case of a timeout. Reading the documentation of WhenAny and looking at your implementation of it helped me to grasp what is going on with how tasks are called and run. One question I had about using WhenAny would be the case where both tasks are trying to change the textbox at the same time? Would this create a deadlock scenario? I suppose two dummie variables could be created to hold the text to be written to the text box and whichever dummie variable had information at the time WhenAny completed, that dummie variable would be written to the text box.
What do you think?
Best regards,
Ben