I have a question regarding the following code segment which I found on Microsoft's C# tutorial web page. In the code they provide a demo of tasks. In the event handler they create a task which updates an unprotected collection.
Is this code thread-safe? In my opinion it's not. What is the best way to make this code thread-safe?
private ArrayList students = new ArrayList(); private void btnCreateStudent_Click(object sender, RoutedEventArgs e) { Student newStudent = new Student(); newStudent.FirstName = txtFirstName.Text; newStudent.LastName = txtLastName.Text; newStudent.City = txtCity.Text; ClearForm(); Task task1 = new Task(() => AddToCollection(newStudent)); task1.Start(); ClearForm(); } private void AddToCollection(Student student) { Thread.Sleep(5000); students.Add(student); int count = students.Count; MessageBox.Show("Student created successfully. Collection contains " + count.ToString() + " Student(s)."); } I disagree with the following statement
students.Add(student); I think it should be protected by a lock.
ArrayListit is leftover from .NET 1.1 days before generics exited. You should be usingList<Student>instead.