dparsons
dparsons

Reputation: 2866

Using MVC3 with Async tasks to update the UI

What I have is an AJAX form on a View that makes a call to the server. This call perform n number of tasks where n is a number decided by records in a database (typically no more than 10 records). Each record corresponds to a Build Definition in TFS so what I am trying to do is get all of these Build Definitions, queue them in TFS, and as each build completes update the UI so that user knows which builds have completed.

Unfortunately I am not sure about how best to do this. I was thinking something along these lines:

        foreach (var dep in builds)
        {
            TFS tfsServer = new TFS(TFS_SERVER_ADDRESS);
            IBuildServer buildServer;
            int id = tfsServer.QueuBuild(dep.TeamProject, dep.BuildDefinition);
            string teamProject = dep.TeamProject;
            Task.Factory.StartNew(() => GetBuildStatus(teamProject, id, tfsServer));

        }

The task that is called is:

        private void GetBuildStatus(string TeamProject, int BuildID, TFS Server)
        {
            Server.GetBuildStatus(TeamProject, BuildID);
            AsyncManager.OutstandingOperations.Decrement();
        }

The problem here is that my Completed method isn't going to get called until all of the builds have completed. How would I go about feeding data back up to the UI a piece at a time?

It is also worth mentioning that the GetBuildStatus method looks like this:

        do
        {
            var build = buildsView.QueuedBuilds.FirstOrDefault(x => x.Id == BuildID);
            if(build != null)
            {
                status = build.Status;
                detail = build.Build;    
            }

        } while (status != QueueStatus.Completed);
        return detail.Status.ToString();

Upvotes: 0

Views: 353

Answers (1)

Ian Mercer
Ian Mercer

Reputation: 39277

Given that the duration of a build will be longer than the timeout for an HTTP request you cannot leave the browser waiting while this happens. You need to return a page and then poll for updates from that page using AJAX. Typically you'd have a timer in javascript that triggers a regular call back to the server to get the updated status information.

But, since you are using .NET you could also consider trying SignalR which lets you use long polling, server sent events or web sockets to wait for updates from the server and it wraps it all up in some easy to implement .NET classes and Javascript.

Upvotes: 1

Related Questions