How to run two threads parallel?

后端 未结 4 992
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-24 15:20

I start two threads with a button click and each thread invokes a separate routine and each routine will print thread name and value of i.

Program runs

4条回答
  •  难免孤独
    2020-12-24 15:59

    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 got a another nice example of 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's "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
        }
    

提交回复
热议问题