c# - 如何并行运行两个线程?

标签 c# multithreading

我通过单击按钮启动两个线程,每个线程调用一个单独的例程,每个例程将打印线程名称和 i 的值。

程序运行完美,但我看到 Thread1() 函数先运行,然后 Thread2() 例程开始,但我尝试运行 Thread1()Thread2() 都是并行的。我哪里出错了?

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)); 
    }
}

最佳答案

这样我就实现了我的目标。这是代码

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();
            }
        }
    }

我从这个 url https://msdn.microsoft.com/en-us/library/dd460705%28v=vs.110%29.aspx 得到了另一个很好的任务库示例.

这是代码

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
    }

关于c# - 如何并行运行两个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29626685/

相关文章:

c# - Active Directory 用户组成员资格 GroupPrincipal

c# - 使用命令行解析器库的列表/数组的默认值

java - 如何继续向执行者提交任务

python - 使用 OpenCV 和 Python 多处理进行持续相机抓取

c++ - 仔细检查锁定问题,c++

c# - Java 中的拖放应用程序,如 .Net 中的 IDesignerHost

c# - 列出可用的 COM 端口

c# - 如何使用sql server 2005在asp.net c#中显示网站中的长内容

c - 互斥量和信号量实际上做了什么?

java - 如何从数据库加载并重置 Web 应用程序中的配置映射