Question

I'm working on Windows Phone 7.1 app and want for several lines of code run for 10 seconds, if succeeds in 10 seconds, continue, if no success, stop the code and display message. The thing is, my code is not a loop - phone tries to fetch data from a server (if internet connection is slow, might take too long).

if (DeviceNetworkInformation.IsNetworkAvailable)
{
    // start timer here for 10s
    WebClient webClient = new WebClient();
    webClient.DownloadStringCompleted += loginHandler;
    webClient.DownloadStringAsync(new Uri(string.Format(url + "?loginas=" + login + "&pass=" + pwd)));
    // if 10s passed, stop code above and display MessageBox
}
Was it helpful?

Solution

You can use something like the following:

HttpClient client = new HttpClient();

var cts = new CancellationTokenSource();
cts.CancelAfter(10000);

try
{
    var response = await client.GetAsync(new Uri(string.Format(url + 
            "?loginas=" + login + "&pass=" + pwd)), cts.Token);
    var result = await response.Content.ReadAsStringAsync();
    // work with result
}
catch(TaskCanceledException)
{
    // error/timeout handling
}

You need the follwoing NuGet packages:

OTHER TIPS

Make that piece of code a method, make that method run separately. Launch a Timer, when 10 seconds elapsed, check the status of the first thread. If it has fetched all that he was supposed to, make use of that, otherwise kill the thread, clean whatever you have to clean and return that message of error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top