简体   繁体   中英

Asynchronous web request not working in WCF

I am using third party API to add log API Call, i want to call this API Asynchronously to does not affect timing for main API call, also this process is low priority (even API result will not used.)

I have tried below code but it seems not work to me:

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);

Can anyone have idea how to call API from WCF asynchronously?

you can create a method like this:

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);
}

then you can call it asynchronously like this:

    Task.Run(() => Call<dynamic>("www.example.com", "body"));

If asynchrony is all that you're looking for then you can achieve just that by using HttpClient with async / await . Then you can either fire & forget, or ensure that it has finished before leaving your calling-method.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM