【问题标题】:Consuming REST (GET) Service from Windows Phone 8.1 [closed]从 Windows Phone 8.1 使用 REST (GET) 服务 [关闭]
【发布时间】:2014-05-27 20:22:51
【问题描述】:

我是 Windows Phone 开发的新手。我想从我的代码向 REST(GET) 服务发出 HTTP 请求。结果将在 Json 中。

我想异步获取我的结果,并且在检索时我想显示进度环。

帮我解决这个问题。提前致谢。

我尝试了以下代码。但是遇到异常

System.Exception 未被用户代码处理 H结果=-2147417842 Message=应用程序调用了为不同线程编组的接口。 (来自 HRESULT 的异常:0x8001010E (RPC_E_WRONG_THREAD)) 源=窗口 堆栈跟踪: 在 Windows.UI.Xaml.Controls.ProgressRing.put_IsActive(布尔值) 在 eBooks.MainPage.GetResultCallBack(IAsyncResult 结果) 在 MS.Internal.Modern.ClientHttpWebRequest.c__DisplayClass1e.b__1c(Object state2) 内部异常:
public void MakeRequest(string requestUrl)
{
    try
    {
        SearchProgress.IsActive = true;
        SearchButton.IsEnabled = false;
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl) as HttpWebRequest;
        request.BeginGetResponse(GetResultCallBack, request);

    }
    catch (Exception)
    {

    }
}

private void GetResultCallBack(IAsyncResult result)
{
    HttpWebRequest request = result.AsyncState as HttpWebRequest;
    if (request!=null)
    { 
        try
        {
            WebResponse response = request.EndGetResponse(result);
            if (response!=null)
            {
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(BookSearch));
                object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
                ebook = objResponse as BookSearch;
            } 
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            SearchProgress.IsActive = false;
            SearchButton.IsEnabled = true;
            DataLoaded(ebook);
        }
    }
}

【问题讨论】:

  • 欢迎来到 Stack Overflow!看起来您希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的编码人员编写代码,但他们通常只有在发布者已经尝试自己解决问题时才会提供帮助。展示这项工作的一个好方法是包含您迄今为止编写的代码、示例输入(如果有的话)、预期输出和您实际获得的输出(控制台输出、堆栈跟踪、编译器错误 - 不管是什么适用的)。 stackoverflow.com/help/how-to-ask
  • 那么,您尝试过的方法有什么问题?

标签: c# xaml rest windows-phone-8.1


【解决方案1】:

异常描述了问题所在。您正在尝试访问 SearchProgress 控件,该控件是在非 UI 线程的 UI 线程上创建的 ProgressRing。为了解决这个问题,您需要从 UI 线程进行更改,为此您需要使用 CoreWindow 调度程序:

CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
    () =>
    {
        Debug.WriteLine("I'm on UI thread");
        SearchProgress.IsActive = false;
        SearchButton.IsEnabled = true;
    }
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多