一、描述
async :返回值需要是Task 、Task<T> 、 void 或者VirtualTask<T>(.Net 7.0)。
Final、示例
using System.Net;
using System.Threading.Tasks;
class Program
{
private static async Task RequestWeb(string url)
{
try
{
WebRequest webRequest = WebRequest.Create(url);
WebResponse webResponse = await webRequest.GetResponseAsync();
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
string text = await reader.ReadToEndAsync();
Console.WriteLine(text);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
static void Main()
{
Task requestTask = RequestWeb("https://www.baidu.com");
while (!requestTask.Wait(10))
{
Console.Write("*");
}
}
}
使用委托实现
using System.Net;
using System.Threading.Tasks;
class Program
{
static void Main()
{
Func<string, Task> RequestWeb = async (url) =>
{
try
{
WebRequest webRequest = WebRequest.Create(url);
WebResponse webResponse = await webRequest.GetResponseAsync();
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
string text = await reader.ReadToEndAsync();
Console.WriteLine(text);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
};
Task requestTask = RequestWeb("https://www.baidu.com");
while (!requestTask.Wait(10))
{
Console.Write("*");
}
}
}
留言