C#方法在调用事件处理程序之前返回

时间:2012-06-26 16:46:26

标签: c# webclient

我的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);
    }

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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