检查网址/网站名称的简单代码是否有效。
这段代码(同步代码)非常完美。当我评论同步代码并取消注释async
代码时,代码无法正常工作。我的async
编程有什么问题?
class Program
{
static StringBuilder urlStatus = new StringBuilder("");
//public static async Task<string> GetHeadersAsync(string url) //Async Code
public static string GetHeadersAsync(string url) ////Sync Code
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";
try
{
//using (var response = await request.GetResponseAsync() as HttpWebResponse) //Async Code
using (var response = request.GetResponse() as HttpWebResponse) ////Sync Code
{
if (response != null && response.StatusCode == HttpStatusCode.OK)
return "HTTP_OK";
return "Error";
}
}
catch (WebException ex)
{
return ex.ToString();
}
catch (Exception ex)
{
return ex.ToString();
}
}
static void Main(string[] args)
{
string lineData;
//content of URLList.txt
//http://www.oracle.com
//http://www.oracletest.com
//http://www.cnn.com
//http://www.cnntest.com
using (StreamReader sr = new StreamReader("URLList.txt"))
{
while ((lineData = sr.ReadLine()) != null)
{
var urlRetStatus = GetHeadersAsync(lineData);
urlStatus.Append(lineData + " " + urlRetStatus.ToString() + System.Environment.NewLine);
}
}
System.IO.File.WriteAllText(@"ErrorURL.txt", urlStatus.ToString());
}
}
答案 0 :(得分:4)
当您调用async
方法时,您将返回表示异步操作的任务。要从该任务中提取实际结果,请使用await
关键字:
Task<string> task = GetHeadersAsync(lineData);
string result = await task;
在您的情况下,您从Main
调用该方法,该方法可能不是async
方法且无法使用await
,因此您需要使用Task.Result
属性:
Task<string> task = GetHeadersAsync(lineData);
string result = task.Result;
请记住,这将阻止调用线程,直到async
操作完成,因此不建议这样做。