0

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

請告訴我們代碼。這個問題不是很明確。 –

+0

向我們展示一些代碼。你遇到了什麼錯誤?這是一個例外嗎? – ColinE

+0

我已經用相關的代碼更新了這個問題。 – Mischif

回答

1

的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(); 
} 
+0

我不調用從MainPage更新UI的函數,而是從自定義類中更新UI。 – Mischif

+0

如何訪問屬於另一個類的成員的ResponseBlock對象?你應該返回到'MainPage'並從這裏調用。我的代碼顯示瞭如何做到這一點 – Ku6opr