【发布时间】:2021-07-19 21:20:38
【问题描述】:
我正在尝试多次发送 HTTP POST 请求,但不是并行发送。我创建了另一个类并将这个函数放入其中:
public async Task<string> sendReqAsync()
{
requestTime = DateTime.Now;
var task = await client.PostAsync("https://api.example.com", content).ContinueWith(async (result) =>
{
responseTime = DateTime.Now;
return await result.Result.Content.ReadAsStringAsync();
});
return task.Result;
}
最后它会在一个按钮的点击事件中被调用:
private async void ManualSendBtn_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
// Here "client" is object of my class that have been initilized in the main WPF function
await client.sendReqAsync().ContinueWith((result) =>
{
var parsedResponse = JObject.Parse(result.Result);
this.Dispatcher.Invoke(() =>
{
ordersListView.Items.Add(new OrderDetailsItem
{
IsSuccessful = bool.Parse(parsedResponse["IsSuccessfull"].ToString()),
ServerMessage = parsedResponse["MessageDesc"].ToString(),
RequestTime = client.requestTime.ToString("hh:mm:ss.fff"),
ResponseTime = client.responseTime.ToString("hh:mm:ss.fff"),
ServerLatency = (client.responseTime - client.requestTime).Milliseconds.ToString()
});
});
});
}
但它只适用于第一次点击(事件发生),而下次点击它会给我:
内部异常 1:AggregateException:发生一个或多个错误。
内部异常 2:AggregateException:发生一个或多个错误。
内部异常 3:ObjectDisposedException:无法访问已处置的 对象。
编辑:以下是建议的编辑代码,但错误未修复。
MyHTTPClient
public class MyHTTPClient
{
private static readonly HttpClient client = new HttpClient();
StringContent content;
public DateTime requestTime;
public DateTime responseTime;
public void configureReq(string oauthToken)
{
var postBodyJSONObject = new
{
body = "value"
};
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", oauthToken);
content = new StringContent(JsonConvert.SerializeObject(postBodyJSONObject), Encoding.UTF8, "application/json");
}
public async Task<string> sendReqAsync()
{
requestTime = DateTime.Now;
var result = await client.PostAsync("https://example.com", content);
responseTime = DateTime.Now;
return await result.Content.ReadAsStringAsync();
}
}
这也是我的窗口初始化函数:
MyHTTPClient client; // Somewhere in the class
public MainWindow() {
client = new MyHTTPClient();
client.configureReq(AUTHORIZATION);
}
【问题讨论】:
-
您使用了
async/await错误。你根本不应该打电话给ContinueWith。删除所有ContinueWith调用并用正确的async/await代码替换它。像这样:``` requestTime = DateTime.Now; var result = await client.PostAsync("api.example.com", content); var responseTime = DateTime.Now;返回结果.Content.ReadAsStringAsync(); ``` -
不要将
await与ContinueWith混用。很确定PostAsync将首先完成result.Result.Content.ReadAsStringAsync运行第二个因此错误。在错误处理方面,延续可能是邪恶的 -
另外,请改掉拨打
task.Result的习惯。一般来说,最好使用(在你的情况下)return await client.PostAsync(因此不需要var task = ...) -
@Neistow 但我需要跟踪我的
POST请求的发送和接收时间。还有另一个好主意来实现这一目标吗?您能否更详细地描述一下?为什么我使用 async/await 错误?怎么写?
标签: c# asynchronous