如何等待文件下载(或验证URL)?

时间:2013-01-28 17:39:28

标签: c# windows-phone-7 windows-phone async-await

我遇到了问题,我想在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");  
    }

我需要的是......

  • 从指定网址下载文件
  • 下载前验证网址
  • if(verfied)then
    • 继续下载并执行其他任务
  • 其他
    • 失败并停止进程,请勿下载!并提供一条消息,指出网址已损坏(无法验证)!

尝试执行“验证”部分,检查网址是否正确并等待回复。我需要某种验证过程的状态,以便继续。

2 个答案:

答案 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方法。