我的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);
}
嗯..你真的知道什么异步的意思吗?如果你只是在等待它,为什么它是异步的? –
http://msdn.microsoft.com/en-us/library/system.net.webclient.downloadstring.aspx否Async – Joe
您是否正在编写Windows 8应用程序? – dlev