为什么我不能将DownloadStringAsync的结果传递给变量?

时间:2013-08-06 22:32:03

标签: c# http asynchronous

我正在使用此代码:

在类的构造函数中:

 this.wc.Credentials = CredentialCache.DefaultCredentials;
 this.wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);

    private void button1_Click(object sender, EventArgs e)
    {

        this.wc.DownloadStringAsync(new Uri("http://url" + this.a[0] + ".aspx"));
    }

public void wc_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
    {
        if (!e.Cancelled && e.Error == null)
        {
            string result = (string)e.Result;
            // do something
            this.a.RemoveAt(0);
            if (this.a.Count > 0)
            {
                Console.WriteLine(this.a[0]);
                // keep retrieving
            }
        }
        else
        {
            // display/handle error
        }
    }

我知道我无法将DownloadStringAsync的结果设置为变量,因为它是void,但如果我尝试在DownloadStringCompletedEvent处理程序中执行此操作,它只会返回空白。我试图将其分成其他类,但我无法从请求中返回任何内容,因为它是异步/无效或无论出于何种原因。

我在一个类中有上面的内容,它在主应用程序类中使用,我不能将http请求的结果设置为主类中的变量。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

你需要看什么? 它将您的源显示为字符串,并可以通过这种方式查看:

public void wc_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
{
    if (!e.Cancelled && e.Error == null)
    {
        MessageBox.Show((string)e.Result);
    }
}
相关问题