我有以下情况。我有一个遍历集合的类,该集合包含需要由某些REST API服务的请求列表。然后,该响应由另一个类处理并返回。顶级将在继续执行之前等待所有请求完成处理。
var results = new BlockingCollection<string>();
Task.WaitAll(requests.Select(request => Task.Run(() =>
{
var payload = new MyRequest()
{
ParameterOne = request.FieldOne,
...
};
var partialResult = this.RequestProcessingUtility.Service(payload);
results.Add(partialResult.Result);
})).ToArray());
// continues...
public Result Convert(MyRequest request)
{
var result = new Result();
var response = this.RestUtility.Execute<Response, Request>(uri, HttpMethod.Get, request);
// processes response into result
return result;
}
public RestResult<TResult> Execute<TResult, TRequest>(string uri, HttpMethod method, TRequest request)
where TResult : class
{
HttpResponseMessage response = null;
var message = this.CreateRequest(uri, method, request);
try
{
Task.Run(() =>
{
try
{
response = HttpClient.SendAsync(message, HttpCompletionOption.ResponseContentRead).Result;
}
catch (Exception exception)
{
throw exception;
}
})
.Wait();
}
catch (AggregateException taskException)
{
// ... something
}
return this.ProcessResult<TResult>(response); // parses HTTP Response
}
如果我在代码中的其他位置同步执行对此API端点的RestUtility调用,它会很好地响应,并迅速启动。但是在此块中调用它会使执行死锁。
我知道我在这里处理异步调用搞砸了,但是我不知道是什么。
谢谢。