我有下一个功能:
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 函数......