Quantcast
Viewing latest article 5
Browse Latest Browse All 5

Task and Async

Hello,

In my program I am trying to implement a try catch with a timeout, where if the code does not execute within a certain amount of time the catch is called. From what I understand, this can be done using task to run a time and running it asynchronously with the try function. I have read through this blog post on crafting a timeout method and also read through the documentation for tasks.

Blog post: https://blogs.msdn.microsoft.com/pfxteam/2011/11/10/crafting-a-task-timeoutafter-method/

I understand the concept of tasks and async but I think I am getting stuck on the implementation of a where to put what code. Below is the code I am using to get the IP address. My question is: where is the best place to create the task? Should the task be its own method? Class? 

public MainPage() 
{
    this.InitializeComponent();

    //Gets the ip address and displays it on the about page
    IPAdressTextBlock.Text = GetLocalIp();

}

//Gets the IP address assigned by the router
        private string GetLocalIp()
        {
            try
            {
                var icp = NetworkInformation.GetInternetConnectionProfile();

                if (icp?.NetworkAdapter == null) return null;
                var hostname = NetworkInformation.GetHostNames().SingleOrDefault(hn => hn.IPInformation?.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId == icp.NetworkAdapter.NetworkAdapterId);

                // the ip address
                return hostname?.CanonicalName;
            } catch
            {
                return "Network not found.";
            }
        }


Viewing latest article 5
Browse Latest Browse All 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>