将异步api调用结果与请求进行匹配



我正在尝试使用httpclient实现异步api调用。我有一个调用,使用一个带有密钥对值的字典将其写回一个数据库,将其绑定到正确的源记录。

我一直纠结于如何将呼叫与原始的更新请求联系起来。

这是工作的重点:

var s_urlList = xmltogo.AsEnumerable().ToDictionary<DataRow, int, string>(row => Convert.ToInt32(row.Field<string>(0)), row => row.Field<string>(1));

IEnumerable<Task<string>> downloadTasksQuery =
from url in s_urlList.Values
select CallAPI(url);
List<Task<string>> downloadTasks = downloadTasksQuery.ToList();
while (downloadTasks.Any())
{
Task<string> finishedTask = await Task.WhenAny(downloadTasks);
downloadTasks.Remove(finishedTask);
string XMLResult = finishedTask.Result.ToString();
}

感谢您的帮助。

我需要将密钥和xml作为两个参数传递给我的方法,然后返回:

Dictionary<int, string> s_urlList = xmltogo.AsEnumerable().ToDictionary<DataRow, int, string>(row => Convert.ToInt32(row.Field<string>(0)), row => row.Field<string>(1));

IEnumerable<Task<(int,string)>> downloadTasksQuery =
from url in s_urlList
select CallAPI(url.Key, url.Value);
List<Task<(int,string)>> downloadTasks = downloadTasksQuery.ToList();
while (downloadTasks.Any())
{
Task<(int, string)> finishedTask = await Task.WhenAny(downloadTasks);

downloadTasks.Remove(finishedTask);
string XMLResult = finishedTask.Result.Item2.ToString();
int key = finishedTask.Result.Item1;
Console.WriteLine("key: " + key.ToString() + "XML: " + XMLResult);
}
var s_urlList = xmltogo.AsEnumerable().ToDictionary<DataRow, int, string>(row => Convert.ToInt32(row.Field<string>(0)), row => row.Field<string>(1));
List<Tuple<string, string>> xmlResults =new  List<Tuple<string,string>>() 
IEnumerable<System.Threading.Tasks.Task<string>> downloadTasksQuery =
from url in s_urlList.Values
select CallAPI(url).ContinueWith(x=> xmlResults.Add(url, x.Result));
List<Task<string>> downloadTasks = downloadTasksQuery.ToList();
await Task.WhenAll(downloadTasks);
foreach (var xmlResult in xmlResults)
{
string url = xmlResult.Item1,
XMLResult = xmlResult.Item2;
// use your result here
}

最新更新