-1

I have this object

public class ObjectList
{
    public string idreturn { get; set; }
}

While running asynchronous requests with Task.Factory.FromAsync, I'm failing to catch the response

foreach (var obj in ObjectList)
{
    var wreq = (HttpWebRequest)WebRequest.Create(Convert.ToString(getURL));
    var taskResp = Task.Factory.FromAsync<WebResponse>(wreq.BeginGetResponse, wreq.EndGetResponse, null);
    taskResp.ContinueWith(tsk => new StreamReader(tsk.Result.GetResponseStream()).ReadToEnd().Trim())
            .ContinueWith((Task<string> trs) => {
                obj.idreturn = trs.Result.ToString();
            });
}

return JsonHelper.JsonSerializer(ObjectList);

What am I missing?

Andrew Diamond
  • 6,295
  • 1
  • 15
  • 33

2 Answers2

0

You're starting an asynchronous operation and then moving on and serializing the object before the asynchronous operation has finished.

Rather than using ContinueWith you should await the value returned from FromAsync to get the results, that way the rest of the code won't continue on until after the request has finished. If you want the requests to all happen in parallel you can construct all of the tasks and then await Task.WhenAll to run the serialization code after the requests have all finished.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • How should I implement the "await" in this code? for: var taskResp = await Task.Factory.FromAsync(wreq.BeginGetResponse, wreq.EndGetResponse, null); I'm getting : Error CS4032 The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.WebRequestCLR.sqlproj – Yaniv Ben Yohana Aug 14 '17 at 17:22
  • @YanivBenYohana If you're not familiar with it at all you should read through a tutorial on the topic. Covering all of what you need to know is beyond the scope of a single SO answer. That code code that you have that is just what you need to be doing, yes, the error that you have with the code tells you precisely what else you need to change. – Servy Aug 14 '17 at 17:24
-1

Thanks to James Manning answer in Getting the Response of a Asynchronous HttpWebRequest question I finally solved the problem.

  var task = MakeAsyncRequest(getURL);
  obj.smsidreturn = task.Result;