从Windows Phone 8.1中使用REST(GET)服务

时间:2014-05-27 20:22:51

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

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

我希望得到我的结果异步并且在重新启动时我想显示进度环。

帮我解决这个问题。在此先感谢。

我尝试了以下代码。但是获得例外

System.Exception was unhandled by user code
  HResult=-2147417842
  Message=The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
  Source=Windows
  StackTrace:
       at Windows.UI.Xaml.Controls.ProgressRing.put_IsActive(Boolean value)
       at eBooks.MainPage.GetResultCallBack(IAsyncResult result)
       at MS.Internal.Modern.ClientHttpWebRequest.c__DisplayClass1e.b__1c(Object state2)
  InnerException:
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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

该异常描述了问题所在。您正在尝试访问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;
    }
);