我正在使用第三方API添加日志API调用,我想异步调用此API以不影响主API调用的时间,此过程也是低优先级(即使API结果也不会使用。)
我试过下面的代码,但似乎对我不起作用:
string strLogURL = "www.example.com";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(strLogURL);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(objAPILog);
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
httpWebRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), httpWebRequest);
任何人都可以知道如何异步调用来自WCF的API吗?
答案 0 :(得分:1)
你可以创建一个这样的方法:
private static T Call<T>(string url, string body, int timeOut = 60)
{
var contentBytes = Encoding.UTF8.GetBytes(body);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = timeOut * 1000;
request.ContentLength = contentBytes.Length;
request.Method = "DELETE";
request.ContentType = @"application/json";
using (var requestWritter = request.GetRequestStream())
requestWritter.Write(contentBytes, 0, (int)request.ContentLength);
var responseString = string.Empty;
var webResponse = (HttpWebResponse)request.GetResponse();
var responseStream = webResponse.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
reader.BaseStream.ReadTimeout = timeOut * 1000;
responseString = reader.ReadToEnd();
}
return JsonConvert.DeserializeObject<T>(responseString);
}
然后你可以像这样异步调用它:
Task.Run(() => Call<dynamic>("www.example.com", "body"));
答案 1 :(得分:1)
如果异步是您正在寻找的所有内容,那么您可以通过D:\
使用HttpClient
/ async
来实现这一目标。然后你可以开火&amp;忘记,或确保在离开你的呼叫方法之前已经完成。
await