【问题标题】:How do I update the UI from a HttpWebRequest?如何从 HttpWebRequest 更新 UI?
【发布时间】:2012-01-24 05:09:16
【问题描述】:

在我的Mainpage.xaml.cs 文件中,我有一个函数可以创建另一个类的实例并尝试使用该实例中的 HttpWebRequest 下载网页。问题是,一旦我成功下载了网页,我就无法将其发送回主 UI 线程。我尝试使用Deployment.Current.Dispatcher.BeginInvoke 将网页发送回我等待的 TextBlock,但是当我尝试时收到错误消息,告诉我无法从其他类访问 TextBlock。有什么方法可以在不使用 LocalStorage 的情况下在两个线程之间传递数据?

编辑:代码如下:

主页:

private void button1_Click(object sender, RoutedEventArgs e)
    {
        Member m = new Member(name, id);
    }

会员等级:

public Member(String Member, String API)
    {
        APIKey = API;
        MemberName = Member;
        this.super = super;
        DoSend(method, string, "", null);
    }

public void DoSend(string method, string url, string body, string mimetype)
    {
        if (WebRequest.RegisterPrefix("https://",System.Net.Browser.WebRequestCreator.ClientHttp)) {
            HttpWebRequest request = WebRequest.Create(makeURI(url)) as HttpWebRequest;

        request.Method = method;
        request.Headers["X-NFSN-Authentication"] = MakeAuthHeader(url,body);
        if (body != "")
        {
            byte[] bodyData = Encoding.UTF8.GetBytes(body);
            request.ContentType = mimetype;
            //Stuff Should Happen Here
        }

        else
            doStuff(request);
        }

public void doStuff(HttpWebRequest httpReq)
    {
        httpReq.BeginGetResponse(r =>
        {
            var httpRequest = (HttpWebRequest)r.AsyncState;
            var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r);

            using (var reader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var response = reader.ReadToEnd();
                ResponseBlock.Text = response; //Invalid cross-thread reference
            }
        }, httpReq);
    }

【问题讨论】:

  • 请给我们看代码。这样的问题不是很清楚。
  • 给我们看一些代码。你遇到了什么错误?是例外吗?
  • 我已经用相关代码更新了问题。

标签: silverlight windows-phone-7 httpwebrequest httpwebresponse


【解决方案1】:

主页:

customClass.DownloadPage((result) =>
{
    textBlock.Text = result;
},
(exception) =>
{
    MessageBox.Show(exception.Message);
});

自定义类:

public void DownloadPage(Action<string> callback, Action<Exception> exception)
{
    WebClient webClient = new WebClient();
    webClient.DonwloadStringCompleted += (s, e) =>
    {
        if (e.Error == null)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                callback(e.Result);
            });
        }
        else
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                exception(e.Error);
            });
        }
    };
    webClient.DonwloadStringAsync();
}

【讨论】:

  • 我不会从 MainPage 调用更新 UI 的函数,而是从自定义类调用。
  • 如何访问属于另一个类的ResponseBlock 对象?您应该返回MainPage 并从这里致电。我的代码展示了如何做到这一点
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-08
  • 2017-04-30
  • 1970-01-01
相关资源
最近更新 更多