我有一個.net網站,我試圖得到幾個web服務調用的結果,在幾個dropdownlist元素之間共享,並行方式。我的問題是所有的下拉菜單都有相同的值,或者有一些值與具有不同值的值相同(可能不是正確的值)。我該如何解決這個問題並行獲取這些東西?同時填寫字典與HttpClient PostAsJsonAsync擴展
代碼更新時間:
using (HttpClient hc = new HttpClient())
{
hc.BaseAddress = new Uri(CatalogUri);
hc.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/jsonp"));
// request for standard options
HttpResponseMessage stdResponse = hc.PostAsJsonAsync(CatalogSearchOptionPath, searchmeta).Result;
List<string> keynames = {"Key3", "Key2","Key1"};
ConcurrentDictionary<string, List<string>> customOptions = new ConcurrentDictionary<string, List<string>>();
IEnumerable<Task<KeyValuePair<string, List<string>>>> tasks = from key in keynames select GetCustomOptionList(key, hc, searchmeta);
customOptions = new ConcurrentDictionary<string, List<string>>(await Task.WhenAll(tasks));
if (stdResponse.IsSuccessStatusCode)
{
string g = stdResponse.Content.ReadAsStringAsync().Result;
stdOptions = Newtonsoft.Json.JsonConvert.DeserializeObject<List<SearchOption>>(g);
//options = response.Content.ReadAsAsync<SearchOption[]>().Result.ToList();
}
}
異步方法做了要求:
private async Task<KeyValuePair<string, List<string>>> GetCustomOptionList(string key, HttpClient client, SearchMetadata sm)
{
sm.OptionFieldName = key;
var response = await client.PostAsJsonAsync(CatalogSpecificOptionPath, sm);
var result = await response.Content.ReadAsStringAsync();
return new KeyValuePair<string, List<string>>(key, Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(result));
}// end task
您是否嘗試過創建''中環Parallel.ForEach' HttpClient的'(HC)? –
不是現在,但不會打敗使用()的目的? – Matt
馬特,移動它也進入循環:) –