I have a webapi that accepts a URI to another web service. The issue is that I need to allow the web service call to last a variable length of time. For example, I need to pass in the URI and let it run for 10 minutes then stop.
I'm not sure how to implement the time portion. Maybe Cancellation token or maybe Stopwatch or maybe Timer? I might be getting something wrong with the async or perhaps need a Task ?
//Model Class: public class TargetInfo { public string TargetEndpoint { get; set; } public long TargetRunTime { get; set; } } //Controller Post call: public System.Web.Http.IHttpActionResult Post([FromBody]TargetInfo request) { _targets.StartEndpointCall(request); return Ok(); //for now } //attempted methods to make timed call: public void StartEndpointCall(TargetInfo tInfo) { lock (_lockObject) { _cancellationSource = new CancellationTokenSource(); CallEndpoint(_cancellationSource.Token, tInfo); } } private void StopEndpointCall() { lock (_lockObject) { using (_cancellationSource) { if (_cancellationSource != null) { _cancellationSource.Cancel(); _cancellationSource = null; } } } } private async void CallEndpoint(CancellationToken cancellationToken, TargetInfo tInfo) { while (!cancellationToken.IsCancellationRequested) { //make call to endpoint using (var client = new HttpClient()) { client.BaseAddress = new Uri(tInfo.TargetEndpoint); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.PostAsJsonAsync("api/target", tInfo); if (response.IsSuccessStatusCode) { //continue to do something } } } } //or perhaps use a Task? private async Task<HttpResponseMessage> CallEndpoint(TargetInfo tInfo) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(tInfo.TargetEndpoint); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // New code: HttpResponseMessage response = await client.PostAsJsonAsync("api/Target", tInfo); if (response.IsSuccessStatusCode) { //do something } return response; } }