1

I am trying to send 100 messages to an web api from a console application. But the program is ending before sending the messages to the web api. If I put Console.ReadLine(); at the end it is working. Can any one help me with this issue?

I've posted the code I used below.

static void Main(string[] args)
{
    CreateLog();
}

private static void CreateLog()
{
    for(int i=0;i<100;i++)
    ProcessLog(new LogMessage() { });         
}

private static void ProcessLog(LogMessage message)
{
    //Post message to web service
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri(@"web api url");
    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));                   
    HttpContent contentPost = new StringContent(
        JsonConvert.SerializeObject(message), 
        Encoding.UTF8, 
        "application/json");
    client.PostAsync("api/xxx", contentPost);
}
NtFreX
  • 10,379
  • 2
  • 43
  • 63
Gangz
  • 86
  • 1
  • 10

1 Answers1

1

The process exits before all threads are have done their work. When the process exits all of its threads shutdown to. The only possiblity you have is to wait for this Task to finish its work. The method Wait can be used to do that.

var result = client.PostAsync("api/xxx", contentPost);
result.Wait();

EDIT

When you want to run some tasks in parallel and then wait for them to finsish you can use ContinueWhenAll.

List<Task> tasks = new List<Task>();
for(bla; bla; bla) {
    //run client posts async
    tasks.Add(client.PostAsync(bla, bla));
}
XYZ()
Task.Factory.ContinueWhenAll(tasks.ToArray(), (Task[] tasks) => {
    // run action when all are done
});

Or you can use the WaitAll or WhenAll method.

XYZ()
Task.WaitAll(tasks.ToArray()):
// or 
await Task.WhenAll(task.ToArray());

More details on those two methods can be found here.

NtFreX
  • 10,379
  • 2
  • 43
  • 63
  • If I use result.wait() ,it won't be asynchronous anymore . – Gangz Jul 29 '16 at 15:16
  • yes. but the problem here is that your async action is still running when the process ends which means the action interupts. at some point you have to wait for the thread.. – NtFreX Jul 29 '16 at 15:17
  • ok.If a method XYZ() is called like this for(int i=0;i<100;i++){ ProcessLog(new LogMessage() { }); } XYZ(); XYZ() method has to wait untill all the 100 messages are posted succeesfully.How can I proceed to XYZ() while all the messages are being processed . – Gangz Jul 29 '16 at 15:19
  • I do not realy understand what you mean but I 'll take a guess. I supose you want to post the web request don't wait for the result and the run the for loop you just posted. so simply make the result variable I suggested global or take it out of the brackages and call result.Wait() in the last line of your console app to ensure the action has ended before you end the process – NtFreX Jul 29 '16 at 15:22