2012-06-26 69 views
0

我的uriRead方法似乎在异步下载完成之前返回,导致方法返回“”。如果我将Thread.Sleep(5000)放在“//在此等待?”然而,它会完成。C#调用事件处理函数之前返回的方法

如何让此函数等待字符串下载完成,并在没有输入静态延迟的情况下立即返回?

public string uriRead(string uri) 
    { 
     string result = ""; 
     WebClient client = new WebClient(); 
     client.Credentials = CredentialCache.DefaultCredentials; 
     client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(AsyncReadCompleted); 
     client.DownloadStringAsync(new Uri(uri)); 
     // Wait here? 
     return result = downloadedAsyncText;  
    } 

    public void AsyncReadCompleted(object sender, DownloadStringCompletedEventArgs e) 
    { 
     Console.WriteLine("Event Called"); 
     downloadedAsyncText = e.Result.ToString(); 
     Console.WriteLine(e.Result); 
    } 
+10

嗯..你真的知道什么异步的意思吗?如果你只是在等待它,为什么它是异步的? –

+0

http://msdn.microsoft.com/en-us/library/system.net.webclient.downloadstring.aspx否Async – Joe

+0

您是否正在编写Windows 8应用程序? – dlev

回答

0

对不起,但正如其他人提到,如果你使用异步,你应该正确使用它。 结果应该在DownloadStringCompletedEventHandler中读取,您不应该等待,这可能会阻止您的应用程序。您的应用程序需要保持响应。如果该方法永不返回呢?

您需要在类中创建一个专用字段private string results_,该字段在事件处理程序中设置。

0

如果你想等待结果,那么你想同步做到这一点,而不是像其他人所说的那样异步。因此,请使用DownloadString方法而不是DownloadStringAsync。

public string uriRead(string uri) 
{ 
    WebClient client = new WebClient(); 
    client.Credentials = CredentialCache.DefaultCredentials;  
    return client.DownloadString(new Uri(uri)); 
}