Amoon has long said to me: When multithreading is used, switching between threads will waste more time than a single thread. However, VB6 has been used for a long time and cannot write multi-threaded things. [of course, if you do not want to play p-code, you can also! But in that case...]
Now. NET is available. I just watched it for two days and found that multithreading in DOTNET is very simple !! Just to check:
I wrote it in C #, because I just got in touch with C #. The time is too short !! Therefore, the implementation method is clumsy! If any of your predecessors can see it, I hope you will give me some advice.
The implementation is as follows:
Design view:
Create a Windows ApplicationProgram, Add button1 and button2 on form1!
CodeIn form1.cs:
Introduced thread namespace:
Using system. Threading;
/// <Summary>
/// Main entry point of the application.
/// </Summary>
[Stathread]
Static void main ()
{
Application. Run (New form1 ());
}
Private void button#click (Object sender, system. eventargs E)
{
T1 T1 = new T1 ();
T2 t2 = new T2 ();
Console. writeline ("St method ------------- {0 }:{ 1}", datetime. Now. Second. tostring (), datetime. Now. millisecond. tostring ());
T1.runtest ();
T2.runtest ();
}
Private void button2_click (Object sender, system. eventargs E)
{
T1 T1 = new T1 ();
T2 t2 = new T2 ();
Thread thd1 = new thread (New threadstart (t1.runtest ));
Thread thd2 = new thread (New threadstart (t2.runtest ));
Console. writeline ("MT method ------------- {0 }:{ 1}", datetime. Now. Second. tostring (), datetime. Now. millisecond. tostring ());
Thd1.start ();
Thd2.start ();
}
Public class T1
{
Public void runtest ()
{
For (INT I = 0; I <500; I ++)
Console. writeline ("thread1: {0}", I );
Console. writeline ("------------- {0 }:{ 1}", datetime. Now. Second. tostring (), datetime. Now. millisecond. tostring ());
}
}
Public class T2
{
Public void runtest ()
{
For (INT I = 0; I <500; I ++)
Console. writeline ("thread2: {0}", I );
Console. writeline ("------------- {0 }:{ 1}", datetime. Now. Second. tostring (), datetime. Now. millisecond. tostring ());
}
}
The final result is as follows:
First comparison:
St method ------------- 3: 656
------------- 5: 921
Interval: 2.265
Mt method ------------- 40: 656
------------- 43: 109
Interval: 2.453
Second comparison:
St method ------------- 29: 859
------------- 32: 109
Interval: 2.25
Mt method ------------- 0: 843
------------- :125
Interval: 2.282
No. Every time it is a single thread, it's faster !!!
As a result, the next thing to consider is when to write a program using multiple threads ???