class Program { static void Main(string[] args) { var result = DownloadStringWithTimeout("http://www.yueyangdujia.com"); Console.WriteLine("异步方法执行中"); for (int i = 0; i < 3; i++) { System.Threading.Thread.Sleep(1000); Console.WriteLine("休息了"+(i+1)+"秒"); } var str= result.Result; //这里使用到异步方法的返回值,需要等待异步方法执行完毕。 Console.WriteLine("异步方法执行后,同步执行以下代码"); Console.WriteLine(str); Console.Read(); } static async Task<string> DownloadStringWithTimeout(string uri) { using (var client=new HttpClient()) { var downloadTask = client.GetStringAsync(uri); var timeoutTask = Task.Delay(3000); var completedTask = await Task.WhenAny(downloadTask, timeoutTask); if (completedTask == timeoutTask) { System.Threading.Thread.Sleep(2000); Console.WriteLine("异步方法执行完成"); return null; } System.Threading.Thread.Sleep(2000); Console.WriteLine("异步方法执行完成"); return await downloadTask; } } }
from : https://www.cnblogs.com/harpz/p/4904742.html
沒有留言:
張貼留言