0

我的 uriRead 方法似乎在异步下载完成之前返回,导致该方法返回“”。如果我把 Thread.Sleep(5000) 放在“//在这里等待?” 但是,它会完成。

我怎样才能让这个函数等待字符串下载完成并在不输入静态延迟的情况下立即返回?

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);
    }
4

2 回答 2

0

如果您想等待结果,那么您希望同步执行,而不是其他人提到的异步执行。所以使用 DownloadString 方法而不是 DownloadStringAsync。

public string uriRead(string uri)
{
  WebClient client = new WebClient();
  client.Credentials = CredentialCache.DefaultCredentials;      
  return client.DownloadString(new Uri(uri));
}
于 2012-06-26T18:04:02.597 回答
0

抱歉,但正如其他人提到的,如果您使用的是 Async,您应该正确使用它。结果应该在 中读取DownloadStringCompletedEventHandler,您不应该等待,这可能会阻止您的应用程序。您的应用程序需要保持响应。如果方法永远不会返回怎么办?

您需要在您private string results_ 在事件处理程序中设置的类中创建一个私有字段。

于 2012-06-26T17:12:03.783 回答