从Async Completion Handler设置TextBlock

时间:2012-10-19 05:04:54

标签: c# asynchronous microsoft-metro

我想根据对Web服务的异步调用的响应,在我的应用的MainPage上设置文本。

我得到一个“应用程序称为为不同线程编组的接口”。所以我知道我需要执行

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

Edit2:我的MainPage类

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)
    {
        ...
    }
}

1 个答案:

答案 0 :(得分:0)

所以我找到了解决问题的解决方案

Delegate 'System.Action<object>' does not take 0 arguments - C# - Task

我设置我的ServerRequest对象来存储当前的同步上下文

ui = TaskScheduler.FromCurrentSynchronizationContext();

然后在我的Response Handler中运行以下命令:

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