try { for (int i = 0; i < tasks.Length; i++) { if (tasks[i].Status == TaskStatus.Faulted) { //获取task中的异常 foreach (var single in tasks[i].Exception.InnerExceptions) { Console.WriteLine(single.Message); } } }
using System; using System.Text; using System.Threading;
namespaceConsoleApp4 { internalclassProgram { privatestaticstring[] words1 = newstring[] { "brown", "jumps", "the", "fox", "quick" }; privatestaticstring[] words2 = newstring[] { "dog", "lazy", "the", "over" }; privatestaticstring solution = "the quick brown fox jumps over the lazy dog.";
privatestaticbool success = false;
privatestatic Barrier barrier = new Barrier(2, (b) => { StringBuilder sb = new StringBuilder(); for (int i = 0; i < words1.Length; i++) { sb.Append(words1[i]); sb.Append(" "); } for (int i = 0; i < words2.Length; i++) { sb.Append(words2[i]);
if (i < words2.Length - 1) sb.Append(" "); } sb.Append(".");
Console.CursorLeft = 0; Console.Write("Current phase: {0}", barrier.CurrentPhaseNumber); if (String.CompareOrdinal(solution, sb.ToString()) == 0) { success = true; Console.WriteLine("\r\nThe solution was found in {0} attempts", barrier.CurrentPhaseNumber); } });
privatestaticvoidMain(string[] args) { Thread t1 = new Thread(() => Solve(words1)); Thread t2 = new Thread(() => Solve(words2)); t1.Start(); t2.Start();
// Keep the console window open. Console.ReadLine(); }
privatestaticvoidSolve(string[] wordArray) { while (success == false) { Random random = new Random(); for (int i = wordArray.Length - 1; i > 0; i--) { int swapIndex = random.Next(i + 1); string temp = wordArray[i]; wordArray[i] = wordArray[swapIndex]; wordArray[swapIndex] = temp; }