How to start two threads in parallel?

I start two threads at the push of a button, and each thread invokes a separate procedure, and each procedure will print the name of the stream and the value i .

The program works fine, but I saw the Thread1() function first, and then the Thread2() procedure Thread2() , but I'm trying to run Thread1() and Thread2() in parallel. Where am I making a mistake?

 private void button1_Click(object sender, EventArgs e) { Thread tid1 = new Thread(new ThreadStart(Thread1)); Thread tid2 = new Thread(new ThreadStart(Thread2)); tid1.Start(); tid2.Start(); MessageBox.Show("Done"); } public static void Thread1() { for (int i = 1; i <= 10; i++) { Console.Write(string.Format("Thread1 {0}", i)); } } public static void Thread2() { for (int i = 1; i <= 10; i++) { Console.Write(string.Format("Thread2 {0}", i)); } } 
+8
multithreading c #
source share
4 answers

in this way I achieve my goal. here is the code

 using System.Threading.Tasks; using System.Threading; class Program { static void Main(string[] args) { Task task1 = Task.Factory.StartNew(() => doStuff("Task1")); Task task2 = Task.Factory.StartNew(() => doStuff("Task2")); Task task3 = Task.Factory.StartNew(() => doStuff("Task3")); Task.WaitAll(task1, task2, task3); Console.WriteLine("All threads complete"); Console.ReadLine(); } static void doStuff(string strName) { for (int i = 1; i <= 3; i++) { Console.WriteLine(strName + " " + i.ToString()); Thread.Yield(); } } } 

I have another good example of a task library from this URL https://msdn.microsoft.com/en-us/library/dd460705%28v=vs.110%29.aspx .

here is the code

 using System.Threading; using System.Threading.Tasks; using System.Net; class Program { static void Main() { // Retrieve Darwin "Origin of the Species" from Gutenberg.org. string[] words = CreateWordArray(@"http://www.gutenberg.org/files/2009/2009.txt"); #region ParallelTasks // Perform three tasks in parallel on the source array Parallel.Invoke(() => { Console.WriteLine("Begin first task..."); GetLongestWord(words); }, // close first Action () => { Console.WriteLine("Begin second task..."); GetMostCommonWords(words); }, //close second Action () => { Console.WriteLine("Begin third task..."); GetCountForWord(words, "species"); } //close third Action ); //close parallel.invoke Console.WriteLine("Returned from Parallel.Invoke"); #endregion Console.WriteLine("Press any key to exit"); Console.ReadKey(); } #region HelperMethods private static void GetCountForWord(string[] words, string term) { var findWord = from word in words where word.ToUpper().Contains(term.ToUpper()) select word; Console.WriteLine(@"Task 3 -- The word ""{0}"" occurs {1} times.", term, findWord.Count()); } private static void GetMostCommonWords(string[] words) { var frequencyOrder = from word in words where word.Length > 6 group word by word into g orderby g.Count() descending select g.Key; var commonWords = frequencyOrder.Take(10); StringBuilder sb = new StringBuilder(); sb.AppendLine("Task 2 -- The most common words are:"); foreach (var v in commonWords) { sb.AppendLine(" " + v); } Console.WriteLine(sb.ToString()); } private static string GetLongestWord(string[] words) { var longestWord = (from w in words orderby w.Length descending select w).First(); Console.WriteLine("Task 1 -- The longest word is {0}", longestWord); return longestWord; } // An http request performed synchronously for simplicity. static string[] CreateWordArray(string uri) { Console.WriteLine("Retrieving from {0}", uri); // Download a web page the easy way. string s = new WebClient().DownloadString(uri); // Separate string into an array of words, removing some common punctuation. return s.Split( new char[] { ' ', '\u000A', ',', '.', ';', ':', '-', '_', '/' }, StringSplitOptions.RemoveEmptyEntries); } #endregion } 
+7
source share

They work in parallel. Here is the edited code to see it better:

  private void test() { Thread tid1 = new Thread(new ThreadStart(Thread1)); Thread tid2 = new Thread(new ThreadStart(Thread2)); tid1.Start(); tid2.Start(); Console.Write(string.Format("Done")); } static void Thread1() { for (int i = 1; i <= 10; i++) { Console.Write(string.Format("Thread1 {0}", i)); Thread.Yield(); } } static void Thread2() { for (int i = 1; i <= 10; i++) { Console.Write(string.Format("Thread2 {0}", i)); Thread.Yield(); } } 

And here is the conclusion: DoneThread1 1Thread2 1Thread1 2Thread2 2Thread1 3Thread2 3Thread1 4Thread2 4Thread1 5Thread2 5Thread1 6Thread2 6Thread1 7Thread2 7Thread1 8Thread2 8Thread1 9Thread2 9Thread1 10Thread2 10

+4
source share

You can use the Parallel.Invoke () method. But it will only work with .Net 4 and above.

  public ParallelDemo() { Parallel.Invoke( () => { PrintCount(-10000, 0); }, () => { PrintCount(1, 10000); } ); } public void PrintCount(int LowLimit , int UpperLimit) { for (int i = LowLimit; i <=UpperLimit; i++) { Console.WriteLine("> {0}" , i); } } 

Output (not for all systems): Screenshot

+3
source share

They start in parallel, but begin with a time delay that is longer than the execution time of each thread. Throw a delay after each Console.WriteLine , and you will see.

By the way, a more elegant way to start a new thread is

 ThreadPool.QueueUserWorkItem(delegate { //code here }); 
+2
source share

All Articles