异步 Web 请求在 WCF 中不起作用
Posted
技术标签:
【中文标题】异步 Web 请求在 WCF 中不起作用【英文标题】:Asynchronous web request not working in WCF 【发布时间】:2017-11-09 16:27:37 【问题描述】:我正在使用第三方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?
【问题讨论】:
【参考方案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"));
【讨论】:
很高兴我能帮上忙。【参考方案2】:如果您只需要异步,那么您可以通过使用HttpClient
和async
/await
来实现。然后你可以触发并忘记,或者在离开你的调用方法之前确保它已经完成。
public void DoSomeWork()
PerformWebWork("http://example.com", new object());
// Perform other work
// Forget webWork Task
// Finish
public async Task DoSomeWorkAsync()
Task webWorkTask = PerformWebWork("http://example.com", new object());
// Perform other work
// Ensure webWorkTask finished
await webWorkTask;
// Finish
public async Task PerformWebWork(string url, object objAPILog)
string serializedContent = new JavaScriptSerializer().Serialize(objAPILog);
using (HttpClient client = new HttpClient())
StringContent content = new StringContent(serializedContent);
HttpResponseMessage postResponse = await client.PostAsync(url, content);
【讨论】:
以上是关于异步 Web 请求在 WCF 中不起作用的主要内容,如果未能解决你的问题,请参考以下文章