在我的Mainpage.xaml.cs
文件中,我有一個函數可以創建另一個類的實例,並嘗試從該實例使用HttpWebRequest下載網頁。問題是,一旦我設法下載網頁,我無法將其發送回主UI線程。我試過使用Deployment.Current.Dispatcher.BeginInvoke
將網頁發送回TextBlock,我有等待,但是當我嘗試時,我收到一個錯誤,告訴我無法從其他類訪問TextBlock。有沒有辦法在兩個線程之間傳遞數據而不使用LocalStorage?如何從HttpWebRequest更新UI?
編輯:下面的代碼:
的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);
}
請告訴我們代碼。這個問題不是很明確。 –
向我們展示一些代碼。你遇到了什麼錯誤?這是一個例外嗎? – ColinE
我已經用相關的代碼更新了這個問題。 – Mischif