user2403909
user2403909

Reputation: 85

Class designs and elegantly wait

I am doing a small project that needs to wait until all jobs are finished. The details are like this:

  1. There is a web server that I can post jobs to it and query the status of the jobs. It has some REST apis to do that.

  2. Each job is represented as a json file that has steps to do something.

  3. I need to post 5 jobs to the server and poll the status of each job every 5 minutes. The return status string will be either "InProgress" or "Success"

  4. The host program should wait until all job statuses are "Success" before continuing the next steps.

I'm having some questions about polling the status of jobs and elegantly waiting for the job statuses to be successes. I currently have a Timer set that triggers every 5 minutes and polls for the job results. And the main thread will do something like:

while(!AllJobsFinished){}

I know this method is bad. So the question is how can I design the classes to wait for completion more elegantly?

Upvotes: 1

Views: 56

Answers (1)

svick
svick

Reputation: 244998

You can represent each job as a separate Task and then use Task.WhenAll() to wait for them to complete:

List<Task> jobs = …;
await Task.WhenAll(jobs);

To get that Task, create an async method that does the polling. If it makes sense, you can combine it into a single method with creating the job:

public Task RunJobAsync(JobData data)
{
    JobId id = await PostJobAsync(data);

    while (true)
    {
        JobStatus status = await QueryJobStatusAsync(id);

        if (status == JobStatus.Success)
            break;

        await Task.Delay(Timespand.FromMinutes(5));
    }
}

Upvotes: 1

Related Questions