如何从 HttpWebRequest 更新 UI?

发布于 2024-12-28 17:48:20 字数 1829 浏览 1 评论 0原文

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

编辑:代码如下:

MainPage:

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

In my Mainpage.xaml.cs file I have a function that creates an instance of another class and tries to download a webpage using a HttpWebRequest from that instance. The problem is, once I've managed to download the webpage I can't send it back to the main UI thread. I've tried using Deployment.Current.Dispatcher.BeginInvoke to send the webpage back to a TextBlock I have waiting, but when I try I get an error telling me that I can't access the TextBlock from the other class. Is there any way to pass data between two threads without using LocalStorage?

EDIT: code below:

MainPage:

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

Member class:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

阳光的暖冬 2025-01-04 17:48:20

主页:

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:

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

CustomClass:

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文