我遇到了问题,我想在Main()
等待,直到Download()
完成。但是,文件下载/检查开始,同时其他行开始执行。
如何在await
?
Main
或其他任何内容等待
private void Main()
{
Download("http://webserver/file.xml");
//Do something here ONLY if the file exists!!
}
//This method invokes the URL validation
private void Download(downloadURL)
{
System.Uri targetUri = new System.Uri(downloadURL);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUri);
request.BeginGetResponse(new AsyncCallback(WebRequestCallBack), request);
}
//In this method the URL is being checked for its validity
void WebRequestCallBack(IAsyncResult result)
{
HttpWebRequest resultInfo = (HttpWebRequest)result.AsyncState;
HttpWebResponse response;
string statusCode;
try
{
response = (HttpWebResponse)resultInfo.EndGetResponse(result);
statusCode = response.StatusCode.ToString();
}
catch (WebException e)
{
statusCode = e.Message;
}
onCompletion(statusCode);
}
//This method does not help! I just added if it could be any useful
private void onCompletion(string status)
{
if (status == HttpStatusCode.OK.ToString())
MessageBox.Show("file exists");
else
MessageBox.Show("file does not exists");
}
我需要的是......
我尝试执行“验证”部分,检查网址是否正确并等待回复。我需要某种验证过程的状态,以便继续。
答案 0 :(得分:1)
应该尝试:
var task = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse,
request.EndGetResponse, null);
var response = task.Result;
答案 1 :(得分:0)
您可以使用ManualResetEventSlim对象。实例化它时将其初始化为true。在OnComplete方法的末尾,调用ManualResetEventSlim对象上的Reset方法。在主应用程序中,您只需要在ManualResetEventSlim对象上调用WaitOne方法。