我正在开发 Windows Phone 7.1 应用程序,希望多行代码运行 10 秒,如果 10 秒内成功,则继续,如果没有成功,则停止代码并显示消息。 问题是,我的代码不是循环 - 手机尝试从服务器获取数据(如果互联网连接速度慢,可能需要太长时间)。
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
}
最佳答案
您可以使用类似以下内容:
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
}
您需要以下 NuGet 包:
关于c# - 让代码运行 X 秒,然后停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23131559/