【发布时间】:2017-10-06 22:45:41
【问题描述】:
作为一个做线程和任务的新手,我在我的小练习应用程序中写了两个线程和一个任务,如下所示:
static List<string> myList = new List<string>(); static void Main(string[] args) { //Run the whole operation both threads and task. Operation(); } static async void Operation() { Task t = Task.Run(new Action(RunThreads)); t.Wait(); //Write the result. WriteMessage(); } static void RunThreads() { //Read thread1. string threadName = "Thread-1"; Thread thread1 = new Thread(() => DoSomething(threadName)); thread1.Name = threadName; thread1.Start(); //Read thread2. threadName = "Thread-2"; Thread thread2 = new Thread(() => DoSomething(threadName)); thread2.Name = threadName; thread2.Start(); } public static void DoSomething(string threadName) { for (int i = 1; i < 10; i++) { myList.Add(string.Format("{0} from thread: {1}", i, threadName)); } } private static void WriteMessage() { foreach (string val in myList) { Console.WriteLine(val); } Console.Read(); }
我希望首先完全执行两个线程,并将值添加到“myList”中。一旦这些线程完成(最终在这两个线程结束时,“myList”将包含 20 个项目......)然后运行“WriteMessage()”方法循环遍历所有这 20 个项目并在控制台中打印它们。
以下是我期望在控制台中写入的输出:
- 1 来自线程:线程 2
- 1 来自线程:线程 1
- 2 来自线程:线程 1
- 2 来自线程:线程 2
- 3 来自线程:线程 2
- 4 来自线程:线程 2
- 3 来自线程:线程 1
- 5 来自线程:线程 2
- 此列表最多可包含 20 项。
(我知道来自“Thread-1”和“Thread-2”的消息顺序可能不同,因为进程将是异步的,但每个应该正好有 10 项)。
我的实现的问题是:在这两个线程完成之前正在执行 WriteMessage() 方法。
【问题讨论】:
-
List<T>不是线程安全的! -
您应该等待线程完成。在
RunThreads的末尾使用thread1.Join()、thread2.Join()。
标签: c# .net multithreading c#-4.0 task