I'm trying to send a HTTP POST request multiple times but not in parallel. I've created another class and put this function into it:
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;
}
And finally it'll be called in an click event for a button:
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()
});
});
});
}
But it works just for the first click (event occurs) and for next click it gives me:
Inner Exception 1: AggregateException: One or more errors occurred.
Inner Exception 2: AggregateException: One or more errors occurred.
Inner Exception 3: ObjectDisposedException: Cannot access a disposed object.
Edit: Below is the edited code as suggested, but the error is not fixed.
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();
}
}
Also here is my window initializer function:
MyHTTPClient client; // Somewhere in the class
public MainWindow() {
client = new MyHTTPClient();
client.configureReq(AUTHORIZATION);
}