WCF service call async function
With async/await you need to make it async all the way through.
Make the service a Task-based asynchronous service
[ServiceContract]
public interface IService1 {
[OperationContract]
Task<string> GetData();
}
With that, it is a simple matter of making the rest of the code async all the way through.
public class http {
public async Task<string> HttpRequestAsync() {
var request = GetHttpRequestMessage();
string str1 = await ExecuteRequest(request);
Console.WriteLine(str1);
return str1;
}
//...code removed for brevity as they are already Task-based
}
This should now allow the function to be used in the service implementation
public class Service1 : IService1 {
public Task<string> GetData() {
http test = new http();
return test.HttpRequestAsync();
}
}
In the original example provided the code was mixing async and blocking calls .Result
, which can lead to deadlocks
Reference Async/Await - Best Practices in Asynchronous Programming
I would also advise making the HttpClient
static and reuse it rather than creating multiple instances and disposing of them.
Reference keep an instance of HttpClient for the lifetime of your application for each distinct API that you connect to.
UPDATE:
Another possibility is that the URL being called is HTTPS.
Consider applying the following before making the request via the HttpClient
//Handle TLS protocols
System.Net.ServicePointManager.SecurityProtocol =
System.Net.SecurityProtocolType.Tls
| System.Net.SecurityProtocolType.Tls11
| System.Net.SecurityProtocolType.Tls12;