Creating Async Chained Tasks in C#

Creating Async Chained Tasks in C#

Scenario : 

Want to design a c# controller with following feature.

# User will submit a request and system update the database with a status immediately .

# System will run some command line to sync source and destination folder which may take hours to complete.

# Once the command line copy / sync process is complete system should update the database the status of completion.

Basically c# should create a async task and run in the background without blocking the main thread. Same time after completion of task at background it run run some other tasks.

Below example will also give tips on running command line scripts to sync two folders using c#

 

 

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace ShipTrack.Controllers
{
    public class SyncController : Controller
    {
        // GET: Sync2
        public ActionResult Index()
        {
            Task.Run(() => DoSomeAsyncStuff());
//system will not wait for the rasks to finish
            return View();
        }




        private static async void DoSomeAsyncStuff()
        {


            Task task = new Task(() => Task1());


            task.Start();

            await task;

            Task task2 = new Task(() => Task2());


            task2.Start();

            await task2;


          
        }





        public static string Task1()
        {
          
            //src folder

            string src = @"E:\Projects\MBRSC\sync\src";

            //dest folder

            string dest = @"E:\Projects\MBRSC\sync\dest";

            Process.Start("cmd.exe", @"/c robocopy " + src + " " + dest + " /e /purge").WaitForExit();

            //after complete return 1
            return "success";

        }


   public static string Task2()
        {

            //src folder

            string src = @"E:\Projects\MBRSC\sync\dest";

            //dest folder

            string dest = @"E:\Projects\MBRSC\sync\dest2";

            Process.Start("cmd.exe", @"/c robocopy " + src + " " + dest + " /e /purge").WaitForExit();

            //after complete return 1
            return "success";

        }
    }
}