简体   繁体   中英

Let code run for X seconds, after that stop

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
}

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM