The previous article describes the simple C # multithreading.ProgramWriting, it should be said that there are not too many difficulties. In this program, we will write a special thread. The two threads need to operate on the same list <int> object:
Code 1 Class Threadcollection {
2 List < Int > Elements = New List < Int > ();
3 Public Threadcollection (){
4 Elements. Add ( 10 );
5 Elements. Add ( 20 );
6 }
7
8 Public Void Run ()
9 {
10 Thread. Sleep ( 1000 );
11 Foreach ( Int Item In Elements ){
12 Console. writeline ( " Item ( " + Item + " ) " );
13 Thread. Sleep ( 1000 );
14 }
15
16 }
17
18 Public Void Add ()
19 {
20 Thread. Sleep ( 1500 );
21 Elements. Add ( 30 );
22 }
23
24 }
25
26
27 Threadcollection Coll = New Threadcollection ();
28 Thread thread3 = New Thread (
29 New Threadstart (Coll. Run)
30 );
31 Thread thread4 = New Thread (
32 New Threadstart (Coll. Add)
33 );
34
35 Thread3.start ();
36 Thread4.start ();
37
At this time, the system will throw an invalidoperationexception. Obviously, we need to modify the program. One way is to get an elments image (snapshot) and operate on the image (snapshot). At this time, the data content is obtained, the classes used are:
System. Collections. objectmodel. readonlycollection. Modify the previous foreach statement:
Foreach (INT item in new readonlycollection <int> (elements )){...}
This method marks the elements in elements. Data insertion is not allowed in elements, so the system still reports an error. The complete solution is to use the lock BLOCK statement, use the lock to pass in the variables to be locked, and then use the {} operation to lock the statements. ExampleCodeAs follows:
Code 1 Lock (Elements ){
2 Foreach ( Int Item In Elements)
3 {
4 Console. writeline ( " Item ( " + Item + " ) " );
5 Thread. Sleep ( 1000 );
6 }
7 }
8
9 //////////////////////////////////////// ///////////////// //
10
11 Lock (Elements)
12 {
13 Elements. Add ( 30 );
14 }
In addition, you can copy the elements data and traverse the copied data. At this time, because the write and read data are two completely different objects, there is no synchronization problem. Therefore, it can also be good luck:
Code 1 Int [] Items;
2 Lock (Elements ){
3 Items = Elements. toarray ();
4 }
5 Foreach ( Int Item In Items)
6 {
7 Console. writeline ( " Item ( " + Item + " ) " );
8 Thread. Sleep ( 1000 );
9 }
Obviously, in the case of a large amount of data, copying takes a long time and occupies more memory. However, this method is easy to maintain and understand. Sometimes, this method is also very effective, because during the copy, there may not be much data written, the data is still written in the background, but the foreground can already operate on some of the data, it does not significantly affect the operation data in the background.