C# 从异步完成处理程序设置TextBlock

C# 从异步完成处理程序设置TextBlock,c#,asynchronous,microsoft-metro,C#,Asynchronous,Microsoft Metro,我想根据对Web服务的异步调用的响应,在我的应用程序的主页上设置文本 我得到了一个“应用程序调用了一个为不同线程封送的接口”。所以我知道我需要执行 MainPage.TB_Response.text = response; 在主线程/主线程上,但我不确定如何进行此操作 编辑:这是我的响应处理程序 private void ReadResponse(IAsyncResult asyncResult) { System.Diagnostics.Debug.Write

我想根据对Web服务的异步调用的响应,在我的应用程序的
主页上设置文本

我得到了一个“应用程序调用了一个为不同线程封送的接口”。所以我知道我需要执行

MainPage.TB_Response.text = response;
在主线程/主线程上,但我不确定如何进行此操作

编辑:这是我的响应处理程序

    private void ReadResponse(IAsyncResult asyncResult)
    {
        System.Diagnostics.Debug.WriteLine("ReadResponse");
        try
        {
            // The downloaded resource ends up in the variable named content. 
            var content = new MemoryStream();

            // State of request is asynchronous.
            //RequestState myRequestState = (RequestState)asyncResult.AsyncState;
            HttpWebRequest myHttpWebRequest2 = (HttpWebRequest)asyncResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)myHttpWebRequest2.EndGetResponse(asyncResult);

            //do whatever
            using (Stream responseStream = response.GetResponseStream())
            {
                responseStream.CopyTo(content);
                byte[] data = content.ToArray();
                if (data.Length > 0)
                {
                    string temp = System.Text.Encoding.UTF8.GetString(data, 0, data.Length);
                    MainPage.TB_Reponse.Text = temp;
                    System.Diagnostics.Debug.WriteLine(temp);
                }
            }

        }
        catch (WebException e)
        {

            System.Diagnostics.Debug.WriteLine(e.Message);
        }
    }
编辑2:我的主页类

public sealed partial class MainPage : Page
{
    public static TextBlock TB_Reponse;
    public MainPage()
    {
        this.InitializeComponent();
        MainPage.TB_Reponse = this.TB_Response;
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {

    }

    private void BTN_Login_Click(object sender, RoutedEventArgs e)
    {
        ...
    }
}

所以我找到了解决问题的办法

我将ServerRequest对象设置为存储当前同步上下文

ui = TaskScheduler.FromCurrentSynchronizationContext();
然后在我的响应处理程序中运行以下命令:

Task.Factory.StartNew(() => 
                            {
                                MainPage.TB_Reponse.Text = temp; //This is run on the same thread as the UI
                            },System.Threading.CancellationToken.None , TaskCreationOptions.None, instance.ui);

您可以显示您的异步调用吗?您还可以使用CoreDispatcher.RunAsyc方法在一个线程上包装调用,该方法将委托代码放入UI线程。您是指使用CoreDispatcher包装响应处理程序还是UI交互代码?您希望在UI线程上运行的任何代码-即。,任何涉及UI控件的内容