1

我想MainPage根据对 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);
        }
    }

Edit2:我的主页类

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

1 回答 1

0

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

委托 'System.Action<object>' 不接受 0 个参数 - C# - 任务

我设置我的 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);
于 2012-10-19T06:17:52.373 回答