public void CheckLicenseCommand() { StartNotification(); if ((string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(Password)) && IsRemote == true) { EndNotification("UserName or Password is empty"); return; } _executedComputer = 0; System.Action DoInBackground = new System.Action(() => { try { CheckLicenses = PrepareCheckLicenseModel(); if (CheckLicenses.Count == 0 && IsRemote == true) { EndNotification("Firm of Operation does not contain any computer!"); return; } TotalComputer = CheckLicenses.Count; ProgressContent = "Checking Computer..."; var counter = CheckLicenses.Count; foreach (var chc in CheckLicenses) { System.Action ChildDoInBackground = new System.Action(() => { using (var detect = new LicenseDetection()) { detect.ExecuteWMIForOneApp(chc, UserName, Password, OprId, CheckList.ToList(), IsRemote); } }); System.Action ChildDoOnUiThread = new System.Action(() => { chc.IsProgress = false; counter--; EndNotification("Operation has finished!!"); }); Canceller = new CancellationTokenSource(); var t3 = Task.Factory.StartNew(() => { using (Canceller.Token.Register(Thread.CurrentThread.Abort)) { ChildDoInBackground(); } }, Canceller.Token); var t4 = t3.ContinueWith(t => { using (Canceller.Token.Register(Thread.CurrentThread.Abort)) { ChildDoOnUiThread(); } }, Canceller.Token); } while (counter != 0) { } if (AutoSave) { SaveCommandsync(); } } catch (System.Exception ex) { EndNotification(ex.Message); return; } }); // start the background task Canceller = new CancellationTokenSource(); var t1 = Task.Factory.StartNew(() => { using (Canceller.Token.Register(Thread.CurrentThread.Abort)) { DoInBackground(); } }, Canceller.Token); // when t1 is done run t1..on the Ui thread. }