我正在尝试使用HttpClient做一个简单的post请求(据我所知,当前正确处理post请求的方法。)然而,代码在timeoutTask.Result上停滞,任务卡在Status上= WaitingForActivation。看一下服务器方面的事情,我可以告诉发送邮件请求并返回数据,我还手动调用了wget并验证了一些文本数据是否正确地从服务器返回给这个帖子请求。
当我简单地调用task.Result时,发生了这种情况,所以我尝试添加一个超时任务,但我必须在异步时犯一些错误,因为它仍然挂在timeoutTask.Result上。
class HttpPostExample
{
private static readonly HttpClient client = new HttpClient();
public void processSentence()
{
string uri = "http://localhost:9000/?properties={%22annotators%22%3A%22tokenize%2Cssplit%2Cpos%22%2C%22outputFormat%22%3A%22json%22}";
string result = postSync(uri, "the quick brown fox jumped over the lazy dog");
Debug.WriteLine(result);
}
public static async Task<string> postAsync(string uri, string postData)
{
var content = new StringContent(postData);
var response = await client.PostAsync(uri, content);
var responseContent = await response.Content.ReadAsStringAsync();
return responseContent;
}
public static async Task<string> runTaskWithTimeout(Task<string> task, double seconds)
{
if (await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(seconds))) == task)
{
// task completed within timeout
return task.Result;
}
else
{
// timeout logic
return "timed out";
}
}
public static string postSync(string uri, string postData)
{
var task = postAsync(uri, postData);
var timeoutTask = runTaskWithTimeout(task, 2.0);
return timeoutTask.Result;
}
}
答案 0 :(得分:0)
由于您从同步方法调用async
方法,因此您可能需要尝试在所有等待行上添加ConfigureAwait(false)
。通常,最好始终使用async
或添加ConfigureAwait(false)
以避免死锁。
查看此博客文章以获取示例:https://medium.com/bynder-tech/c-why-you-should-use-configureawait-false-in-your-library-code-d7837dce3d7f