【问题标题】:GetData from server Windows 8从服务器 Windows 8 获取数据
【发布时间】:2013-12-09 08:33:25
【问题描述】:

我有下一个功能:

private void getAllData()
    {
        HttpWebRequest request = HttpWebRequest.CreateHttp("http://webservice.com/wfwe");
        request.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), request);
    }
        void GetResponsetStreamCallback(IAsyncResult callbackResult)
    {
        HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
        using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
        {
            string result = httpWebStreamReader.ReadToEnd();
            GetApplications(result);
        }
    }

然后我填写堆栈面板:

private void GetApplications(string result)
    {
        var ApplicationsList = JsonConvert.DeserializeObject<List<Applications>>(result);
        foreach (Applications A in ApplicationsList)
        {
            foreach (ApplicationRelation SCA in A.ApplicationRelations)
            {
                if (SCA.ApplicationSubcategory != null)
                {
                    #region Fill Customer Research Stack
                    if (SCA.ApplicationSubcategory.subcategoryName == "Customer Research")
                    {
                        if (TestStack.Children.Count == 0)
                        {
                            ApplicationTile AT = FillDataForApplicationTile(SCA);                                
                            AT.Margin = new Thickness(5, 0, 5, 0);
                            TestStack.Children.Add(AT);
                        }
                    }
                    #endregion
                }
            }
        }
    }

代码在以下位置失败:

如果(TestStack.Children.Count == 0)

错误:应用程序调用了为不同线程编组的接口。 (来自 HRESULT 的异常:0x8001010E (RPC_E_WRONG_THREAD))

我怎样才能将我的请求从 void 重写为字符串,所以我可以这样做:

GetApplications(await getAllData())

为 dcastro 编辑 2:

编辑 3:

谢谢它的工作,但我正在寻找这样的东西:

//修改了你的代码:

GetApplications(getAllData2().Result);

private async Task<string> getAllData2()
    {
       string uri = "http://webservice.com/wfe";
       var client = new HttpClient();
       HttpResponseMessage response = await client.GetAsync(uri);
       var result = await response.Content.ReadAsStringAsync();
       return result.ToString();
    }

但不知何故,我的构造没有进入 GetApplication 函数...

【问题讨论】:

  • 你能给我们看一下调用getAllData的代码吗?
  • 我不认为将您的方法更改为像GetApplications(await getAllData()) 那样工作可以解决问题。我认为您正在尝试从非 UI 线程访问 TestStack,这是一个 UI 元素。如果您可以发布更多代码,我可能会提供更多帮助。
  • 在您当前的方法(编辑 3)中,.Result 导致死锁。阅读:blog.stephencleary.com/2012/07/dont-block-on-async-code.html

标签: c# windows-8 windows-8.1


【解决方案1】:

不要使用AsyncCallback(我很确定它是在非UI线程中运行GetResponsetStreamCallback),而是尝试像这样获取您的数据:

private async void getAllData()
   string uri = "http://webservice.com/wfwe";
   var client = new HttpClient();

   HttpResponseMessage response = await client.GetAsync(uri);

   string body = await response.Content.ReadAsStringAsync();

   GetApplications(body);
}

这将异步调用您的 web 服务(在await Client.sendMessageAsync(msg); 行),并在收到响应时返回原始 UI 线程。这样,您可以更新 UI 元素,例如您的 TestStack

编辑修复错误

【讨论】:

  • 错误 4“System.Net.Http.HttpClient”不包含“sendMessageAsync”的定义,并且没有扩展方法“sendMessageAsync”接受“System.Net.Http.HttpClient”类型的第一个参数可以找到(您是否缺少 using 指令或程序集引用?)
  • 在我的问题中为你添加了截图
  • 在您当前的方法中,.Result 导致了死锁。阅读:blog.stephencleary.com/2012/07/dont-block-on-async-code.html
【解决方案2】:

试试这个。

private async Task<string> getAllData()
{
    string Result = "";
    var http = new HttpClient();
    var response = await http.GetAsync("http://webservice.com/wfwe"); // I am considering this URL gives me JSON
    if (response.StatusCode == System.Net.HttpStatusCode.OK)
    {
        Result = await response.Content.ReadAsStringAsync(); // You will get JSON here
    }
    else
    {
        Result = response.StatusCode.ToString(); // Error while accesing the web service.
    }

    return Result;
}

private async Task GetApplications(string result)
{
    var ApplicationsList = JsonConvert.DeserializeObject<List<Applications>>(result);
    foreach (Applications A in ApplicationsList)
    {
        foreach (ApplicationRelation SCA in A.ApplicationRelations)
        {
            if (SCA.ApplicationSubcategory != null)
            {
                #region Fill Customer Research Stack
                if (SCA.ApplicationSubcategory.subcategoryName == "Customer Research")
                {
                    if (TestStack.Children.Count == 0)
                    {
                        // This will update your UI using UI thread
                        await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
                        {
                            ApplicationTile AT = FillDataForApplicationTile(SCA);
                            AT.Margin = new Thickness(5, 0, 5, 0);
                            TestStack.Children.Add(AT);
                        });
                    }
                }
                #endregion
            }
        }
    }
}

【讨论】:

  • 你能建议,我怎样才能重写我原来的:private void getAllData() void GetResponsetStreamCallback(IAsyncResult callbackResult) 成1个函数,这样我就可以像这样使用它们:string a = new Function () ; // 由以上两个组成
  • getAllData() & GetResponsetStreamCallback(IAsyncResult callbackResult) 已合并。您现在可以拨打await GetApplications(await getAllData())
猜你喜欢
  • 1970-01-01
  • 2021-10-21
  • 2017-11-20
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 2022-11-21
  • 1970-01-01
相关资源
最近更新 更多